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

Proxy Pattern

References https://refactoring.guru/design-patterns/proxy https://en.wikipedia.org/wiki/Proxy_pattern proxy: agent, substitute What is the Proxy Pattern? Structural design pattern By placing an agent in front of the real service, the client’s access to the real service can be controlled by the agent. Situation - When do you need to control access to the real service? There is an object that can consume a lot of resources by connecting to the DB. This object is executed occasionally. To address this, you might consider lazy initialization. ...

October 12, 2020

Abstract Factory Pattern

References https://refactoring.guru/design-patterns/abstract-factory What is the Abstract Factory? It is a creational design pattern. It is a pattern that allows you to create a family of related objects without specifying their concrete classes. Original English Abstract Factory is a creational design pattern that 1) lets you produce 2) families of related objects 3) without specifying their concrete classes. let you produce: That is, the client depends on the factory to create products. ...

October 11, 2020

Adapter Pattern

Source https://refactoring.guru/design-patterns/adapter What is the Adapter pattern? Structural pattern A design pattern that allows two incompatible interfaces to collaborate. Situation Goal We want to create a stock market monitoring application. Method Receive stock data in XML format. Analyze it using an Analytics Library and display graphs. Problem However, there is a problem. The Analytics Library accepts data in JSON format for analysis. In other words, the format of the stock data provider and the format of the program that analyzes the data do not match. ...

October 11, 2020

Bridge Pattern

References https://refactoring.guru/design-patterns/bridge https://en.wikipedia.org/wiki/Bridge_pattern Design Patterns: Elements of Reusable Object-Oriented Software (link) https://archive.org/details/designpatternsel00gamm/page/151 What is the Bridge Pattern? Structural design pattern Guru Definition A pattern that separates a large class or a set of highly related classes into two hierarchies. GoF-DesignPattern Definition A pattern that decouples an abstraction from its implementation so that the two can vary independently. Abstraction and Implementation Abstraction and implementation are exactly as Robert Martin described. In the explanation of DIP, Keyboard and Printer correspond to implementation, and Copy can be seen as corresponding to abstraction. That is, Copy is a high-level policy corresponding to the inherent abstract part of the application. Recall that the low-level policy that concretely performs the abstract content of copy was keyboard and printer. The Bridge Pattern goes further, making abstraction an abstract class to allow for the expansion of high-level policies. Analogy - Subtitle (Humans think abstractly) Pick up a spoon and eat rice. Spoon -> It could be a spoon from a restaurant or a spoon from home. Rice could also be rice cooked at a specific time in a restaurant, or leftover rice at home. To satisfy hunger, one performs the act (abstraction) of picking up a spoon and eating rice. ...

October 11, 2020

Builder Pattern

References https://refactoring.guru/design-patterns/builder (Builder pattern explanation) https://projectlombok.org/features/Builder (Lombok) What is Builder? Creational design pattern A design pattern that allows you to construct complex objects step-by-step. Allows you to create different types of objects with the same construction code. Situation You need to create a complex object with many fields and nested objects. Not Recommended Method 1 - Implementation via Class Inheritance Method Description Create a base class Suppose you create a base class called House. This class has a roof, windows, and exterior walls. You make it with specific field values. In other words, you create classes like CabinHouse and BrickHouse. For example, the exterior wall of CabinHouse is wood, and for BrickHouse, it is brick. For extension - create a subclass If you want to make a cabin house with a storage room, you inherit from CabinHouse and add a storage room. Problems You end up with countless subclasses Because you have to create a new subclass for every new parameter. The hierarchy can become deep Inheritance forms a hierarchical structure. If you want to extend not with an annex but with a style (e.g., modern), you have to make it one level deeper. Not Recommended Method 2 - Giant Constructor Method Description Write a constructor that takes all possible parameters. Problems You have to consider unnecessary parameters and put them as arguments As shown on the left of the figure above, even when creating a regular house with only a storage room, you have to consider other options and put null for them. It’s hard to figure out the meaning of each argument When there are many parameters, it’s hard to know what each argument means. Solution - Builder Pattern The Builder pattern moves the object creation code outside the class to be created. It delegates the creation responsibility to individual objects called builders. These builders: ...

October 11, 2020

Dependency Inversion Principle

Previously, we learned about OCP (Open/Closed Principle) and LSP (Liskov Substitution Principle). OCP is the principle of allowing changes but preventing modifications, and LSP is the principle that a base class can be replaced by its subclass. Here, I will talk about the structure that arises from strictly applying these two principles. This structure itself becomes a principle, and its name is the Dependency Inversion Principle. What’s Wrong with Software? As developers, we often drive ourselves into bad design. Why does this happen? The core of the problem is that we haven’t defined what bad design is. ...

October 11, 2020