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

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

Flyweight Pattern

References: Refactoring Guru - Flyweight Pattern Original Korean post What is the Flyweight Pattern? The Flyweight Pattern is a structural design pattern that saves memory by sharing common parts of state between multiple objects, instead of keeping all data in each object. In other words, it is a caching technique for objects. Situation Imagine a shooting game where players fire various types of projectiles: bullets, missiles, and shotgun shells. Shortly after starting, the game runs out of memory and crashes. ...

October 12, 2020

Iterator Pattern

Iterator Pattern Reference https://refactoring.guru/design-patterns/iterator Definition Behavioral design pattern A pattern that encapsulates the behavior of an object and delegates requests to the object. A design pattern that allows you to traverse elements of a collection without knowing its underlying structure. Situation - Traversing Various Types of Collections - You need to traverse various types of collections. Bad Approach - Implementing Traversal Algorithms in the Collection Problems If the data structure is complex, traversal can be difficult and there can be many types. For example, in a tree, you can traverse using DFS, BFS, or even randomly. If you implement all traversal algorithms in the collection, it becomes messy. The main function of a collection is efficient storage, after all. The client code becomes dependent on specific collections. Even though the client doesn’t care how the data is stored, it ends up depending on the collection because each collection provides different ways to access its elements. Solution - Separate the Traversal Algorithm! The core of the iterator pattern is to separate the traversal algorithm from the collection into an object called an iterator. Implementation and Benefits Separate the traversal part into a class called iterator. You can encapsulate the details of traversal (e.g., current position, how many elements are left). The responsibility for traversal is given to the iterator. Implement main methods to fetch elements. This allows you to traverse all elements. Ensure all iterators implement the same interface. This allows client code to use collections and traversal algorithms interchangeably. Structure 1. Iterator Implements the algorithm needed to traverse a collection. Fetch the next element Get the current position Restart the iteration, etc. 2. Concrete Iterators Implements specific algorithms for traversal. The iterator tracks its own progress, so multiple iterators can traverse the same collection independently. 3. Collection Declares one or more methods to obtain an iterator. 4. ConcreteCollection Returns a new iterator instance each time the client requests one. 5. Client Uses the collection and iterator through their interfaces. The client does not create the iterator; the collection does. In special cases, the client may create its own iterator, e.g., if it wants a custom iterator. Question Even though the collection interface claims to be type-agnostic, if the collection is a tree or a list, the traversal may differ, violating LSP (Liskov Substitution Principle). ...

October 12, 2020

Mediator Pattern

Mediator Pattern Reference https://refactoring.guru/design-patterns/mediator Definition Behavioral design pattern A pattern about how objects communicate within a group. A design pattern that restricts direct communication between objects and forces them to communicate through a mediator object. Situation - Communication Between Components in a Dialog Imagine a dialog for creating and editing a customer’s profile. This dialog contains various form controls, e.g., text fields, checkboxes, buttons. Key Point How should components communicate within a form? ...

October 12, 2020

Memento Pattern

Memento Pattern Reference https://refactoring.guru/design-patterns/memento memento: a souvenir to remember a person or place Definition Behavioral design pattern A pattern that encapsulates the behavior of an object and delegates requests to the object. A design pattern that encapsulates implementation details while allowing you to save or restore the previous state of an object. Also called the Snapshot Pattern. Situation - Implementing Undo Feature in an Editor Program Imagine an editor program. This program allows not only text editing but also text decoration and image insertion. Problem How can we implement the undo feature? To implement the undo feature… Before performing an operation, save the state of all objects and put them in storage. Later, when the user decides to revert, retrieve the state of the objects from storage. Set the app’s current state based on that state. How should we read the object’s state at this time? ...

October 12, 2020