Observer Pattern

Observer Pattern References https://refactoring.guru/design-patterns/observer https://ko.wikipedia.org/wiki/%EC%98%B5%EC%84%9C%EB%B2%84_%ED%8C%A8%ED%84%B4 Intent Classification Behavioral design pattern A pattern about how objects communicate within a group. Definition (guru) A pattern that defines a subscription mechanism to notify multiple objects about events that happen to the object they are observing. (wiki) A design pattern in which observers, who are interested in changes to an object’s state, register themselves with the object, and the object notifies each observer directly via methods whenever its state changes. Problem Situation - Notifying Events There are two types of objects: Customer and Store. Customers are interested in the latest iPhone model that will soon be sold at the Store. Problem How can customers buy the product as soon as the latest iPhone is available in the store? Bad Approaches [Method 1] Customer visits every day Customers visit the store every day to check if the latest iPhone has been released. Drawbacks Customers may visit the store even if the product hasn’t been released, resulting in unnecessary effort. [Method 2] Store notifies all customers The store sends emails to all customers whenever a new product is released. This avoids unnecessary visits by customers. Drawbacks Customers who are not interested in the new product still receive notifications, which can be annoying. The store wastes resources. From a programming perspective, the problems can be summarized as: ...

October 18, 2020

State Pattern

State Pattern Three-line summary A behavioral design pattern A pattern that encapsulates the behavior of an object and delegates requests to the object A pattern that changes the behavior as the object’s state changes References https://refactoring.guru/design-patterns/state https://en.wikipedia.org/wiki/State_pattern Intent Classification Behavioral design pattern A pattern that encapsulates the behavior of an object and delegates requests to the object. Definition A design pattern that changes the behavior as the object’s state changes. Because of this, it may appear as if the object’s class has changed. Problem Situation - Finite State Machine The State Pattern is closely related to the concept of a finite state machine. ...

October 18, 2020

Strategy Pattern

Strategy Pattern Reference https://refactoring.guru/design-patterns/strategy Intent Classification Behavioral design pattern A pattern that encapsulates the behavior of an object and delegates requests to the object. Definition A pattern that defines a family of algorithms, encapsulates each one as a separate class, and makes them interchangeable. Problem Situation Let’s think about a navigation app. In the early stages of development, a feature was created to suggest routes with scenic views. Over time, more requirements were added: Added a feature to provide walking routes… Added a feature to provide routes using public transportation… Even added a feature to provide routes passing through specific cities. Problem The logic for providing routes was written in the main class, so every time a new feature was added, the code in the main class doubled in length. Also, because the logic was not separated, bugs occurred whenever the algorithms were modified or improved. How can we create a better structure? Solution Key Point Separate each algorithm into its own class and use an interface to utilize the algorithms. Method Terminology The Navigator is called the context, and the algorithms for selecting a specific route are called strategies. The reason it’s called context is to emphasize the meaning of the context in which the strategy is used. ...

October 18, 2020

Template Pattern

References https://refactoring.guru/design-patterns/template-method Intent Category behavioral design pattern A behavioral class pattern that uses inheritance to distribute behavior among classes. Definition A pattern where the skeleton of an algorithm is defined in a superclass, and subclasses override specific methods without changing the algorithm’s structure. Problem Situation Imagine a data mining app. This app analyzes corporate documents. Users provide data. The app parses the data in a unified format, analyzes it, and extracts meaningful information. Problem Adding Support for More Input Types Initially, only Doc files were supported for data mining, but over time, csv and pdf files were also supported. Problem Recognition The three classes have similar code. They all follow the same procedure: read file -> extract data -> parse data -> analyze data -> report results -> close file. The doc, csv, and pdf classes have duplicated code. ex:) openFile, analyzeData, sendReport, closeFile There is a lot of branching logic. The client code calls each class’s methods with branching logic. How can we avoid duplication in classes with the same structure? ...

October 18, 2020

Visitor Pattern

References https://refactoring.guru/design-patterns/visitor Intent Category behavioral design pattern A pattern that encapsulates the behavior of objects and delegates requests to objects. Definition A pattern that separates algorithms from objects. Problem Situation You are developing a terrain information app composed of a large graph. Nodes can be things like cities or libraries. If there is a road between nodes, they can be connected. The node class represents the type of node, and each specific node is an object. Requirement You are asked to export the graph in XML format. Bad Approach Method - Add logic to the node Add an XML exporting method to the node. Find connected nodes and recursively convert them to XML. Problems Violates SRP. The main responsibility of the node is to work with geographic data, but now it is also asked to export XML files. Violates OCP. You have to change existing logic to add new features, which can cause unexpected bugs. If more features are requested, the logic gets even messier. If you are asked to export to CSV as well as XML, you have to modify the existing logic again. Solution Core Idea Minimize changes to existing logic and move new logic to another class! ...

October 18, 2020

Chain Of Responsibility Pattern

Chain Of Responsibility Pattern Reference https://refactoring.guru/design-patterns/chain-of-responsibility What is Chain of Responsibility? Behavioral object pattern A pattern about how groups communicate. A pattern that passes requests along a chain of handlers. Each handler in the chain decides whether to process the request or pass it to the next handler. Situation Online Ordering System Requirements Only authorized users can create orders (restrict system access). Only admin users can view all information about all orders. Approach These checks must be performed sequentially: Check credentials (authentication) If credentials are wrong or authentication fails, the process stops. Grant appropriate permissions (authorization) Problem - Adding More Requirements Over time, new requirements are added: Add validation to avoid sending raw order data for security reasons. Check for brute force password cracking by monitoring repeated failed attempts from the same IP. Add caching for performance. If all this logic is implemented in a single object, the code grows, becomes harder to maintain, and is not reusable. Solution - Create a Chain of Handlers! Handler The chain of handlers passes specific behaviors to handler objects. Each check can be a class with a single method. Request data is passed as arguments to these methods. Applying as a Chain Handlers are linked in a chain, each with a reference to the next handler. Each handler can process the request or pass it to the next handler. The request traverses the chain until all handlers have processed it or one stops the process. Point A handler can decide to stop processing at any point. Application In the ordering system, validation, authentication, etc. can each be a handler with a single method. If a handler’s check passes, the request is passed to the next handler. Thus, a series of handlers forms a chain of responsibility. Another Approach - Only One Handler Processes the Request In some cases, only one handler in the chain processes the request (or none). If a handler can process the request, it does so and stops; otherwise, it passes the request to the next handler. This is common in GUI systems. Note All handlers must implement the same interface. If handlers depend on concrete handlers, you lose flexibility in ordering and reuse. Structure 1. Handler Interface for all concrete handlers. Declares a single method for processing requests. May also have a method for setting the next handler in the chain. 2. BaseHandler (Optional) Contains code common to all handlers. 3. ConcreteHandlers Contain the logic for processing requests. Each handler must decide whether to process the request or pass it on. Usually, handlers are self-contained and immutable. 4. Client Sets up the chain, either once or dynamically. Requests do not have to start at the first handler; they can start at any handler in the chain.

October 12, 2020

Command Pattern

Command Pattern References https://refactoring.guru/design-patterns/command http://aeternum.egloos.com/v/2948571 Definition Behavioral design pattern A pattern that encapsulates behavior in an object and delegates requests to the encapsulated object. A design pattern that turns a request into a stand-alone object containing all information about the request. This allows you to parameterize methods with different requests, delay or queue request execution, and support undoable operations. Situation - Building a Text Editor App Suppose you are building a text editor app like Hangul or Word. Problem How should you build a toolbar with various buttons? Bad Approach - Creating Subclasses #### Method - Create a subclass of Button for each button, with the code to execute for that button. #### Problems 1. Many subclasses are created. - If the Button class changes, its subclasses may break. 2. Duplication can occur. - For example, SaveButton, SaveMenuItem, and SaveShortcut all perform the same save operation but are implemented as different classes. Solution - Layering, Delegating Cause of the Problem This happens because the roles of the GUI and business logic are not separated. Applying SRP (Single Responsibility Principle) solves this, usually by layering. Method Layering - The GUI renders images, receives input, sends requests with parameters to the business logic, and displays the result. - The business logic performs the requested operation. Command Pattern The Command Pattern goes further by preventing the GUI from calling business logic directly. Implementation Steps Extract detailed requests into separate command classes, each with a method to trigger the request (usually with no parameters). The details of the request (which object, which method, which arguments) are encapsulated in the command object. Command objects act as a link between various GUI and business logic objects. The GUI only needs to call the execute method of the appropriate command, without knowing about the business logic object. Implement all commands with the same interface. Benefits: The GUI does not depend on specific commands. The GUI’s behavior can be changed at runtime. Commands can be stored in containers. Question - What about parameters? Command methods do not take parameters, but business logic often needs them. How is this handled? Parameters are considered part of the detailed request. You implement a command class for each combination of business logic and parameters. Thus, the command pattern structure in this example is as follows: No need to create many subclasses. The Button class only needs a reference to a command object. All buttons for the save operation can use the same save command without duplication. Additional benefits: ...

October 12, 2020

Composite Pattern

References https://refactoring.guru/design-patterns/composite https://en.wikipedia.org/wiki/Composite_pattern What is the Composite Pattern? Structural design pattern Allows you to compose objects into tree structures (part-whole hierarchies) Lets you treat these objects as if they were individual objects. Situation Consider an ordering system. There are two types of objects: boxes and products. A large box can contain smaller boxes and products. An order can be an unpackaged product or a box containing products or other boxes. Goal Let’s find the price of a specific box or product in an order! ...

October 12, 2020

Decorator Pattern

References https://refactoring.guru/design-patterns/decorator What is the Decorator Pattern? Structural design pattern When you want to add new functionality to an existing object, you wrap the original object inside a wrapper object that has the new functionality. Situation This situation deals with problems that arise as features expand. Initial Imagine a notification library. This library takes a message and sends it via email. Structure Notifier A library with notification functionality. It receives a message and sends it via email using the send method. Application Holds a Notifier and has a method to send messages through it. Extension 1 Based on user feedback, you want to send notifications not only by email but also by SMS, Facebook, and Slack. This is solved by having SMS, Facebook, and Slack inherit from Notifier and implement send(). Extension 2 More feedback: users want to send notifications through multiple channels at the same time. Problematic Approach 1 Create a class with methods for all notification features. (Application uses a single Notifier to send messages.) This would require 2^n-1 classes to cover all combinations (binomial theorem). Problematic Approach 2 What about just using inheritance? This has two problems: You can’t change behavior at runtime (inheritance is determined at compile time). Most languages don’t support multiple inheritance, so you can’t inherit multiple features. Solution Prefer Aggregation or Composition over Inheritance A whole object holds references to part objects. This is called a Wrapper. An object can delegate work to other objects. With this structure, you can decide the container’s behavior at runtime and use the features of multiple classes via delegation. ...

October 12, 2020

Facade Pattern

References https://refactoring.guru/design-patterns/facade The interface described here refers to the meaning of API or GUI, not Java’s interface keyword. Interface is the point or boundary where information or signals are exchanged between two different systems or devices. What is the Facade Pattern? Structural design pattern Provides a simplified interface to a library, framework, or a set of complex classes (or subsystems). Situation The application needs to work with objects from various complex libraries and frameworks. Problem If the application directly uses libraries and frameworks, the business logic becomes tightly coupled to them. ...

October 12, 2020