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

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