Skip to content

Commit afcd694

Browse files
committed
翻訳
1 parent 70bb52b commit afcd694

2 files changed

Lines changed: 310 additions & 0 deletions

File tree

Lines changed: 310 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,310 @@
1+
---
2+
title: GoF Design Patterns
3+
date: 2026-01-12
4+
category: Coding
5+
description:
6+
tags: [Coding, DesignPattern]
7+
recommended: true
8+
thumbnail: assets/img/ogp.png
9+
---
10+
11+
Hello! This is Pan-kun.
12+
13+
This time I'll go back to basics and organize/explain the GoF (Gang of Four) design patterns. I have difficulty remembering proper nouns, so there may be omissions or slight variations in wording, but I will clearly convey the main ideas and practical caveats. I will list sources (URLs and quoted excerpts) at the end of the article as evidence for factual claims. When adopting these patterns in production, always consult primary sources (the original text or trusted references).
14+
15+
## Introduction
16+
17+
"GoF" (Gang of Four) refers to the book published in 1994, "Design Patterns: Elements of Reusable Object-Oriented Software," which collected reusable object-oriented design solutions (patterns). The 23 patterns summarized by the GoF are generally classified into three categories:
18+
19+
- Creational: deal with object creation mechanisms
20+
- Structural: deal with composition of classes and objects
21+
- Behavioral: deal with communication between objects and defining algorithms
22+
23+
Patterns are not rigid "answers" but rather design recipes or templates. Advances in language features and frameworks can make some patterns unnecessary—or conversely, overusing patterns can introduce unnecessary complexity. Adopt patterns with judgement appropriate to the use case.
24+
25+
Evidence (excerpt):
26+
- "A software design pattern describes a reusable solution to a commonly needed behavior in software." — Software design pattern (Wikipedia)
27+
28+
[!CARD](https://en.wikipedia.org/wiki/Software_design_pattern)
29+
30+
- "Design Patterns: Elements of Reusable Object-Oriented Software (1994) is a software engineering book describing software design patterns." — Design Patterns (Wikipedia)
31+
32+
[!CARD](https://en.wikipedia.org/wiki/Design_Patterns)
33+
34+
The citations above are intended as general references. When implementing or adopting a pattern, check the original works and concrete language-specific examples.
35+
36+
## Brief explanations of each category
37+
38+
- Creational
39+
Patterns concerned with how objects are created. By separating construction logic, you can improve dependency management, testability, and extensibility.
40+
41+
- Structural
42+
Patterns concerned with composing classes or objects into larger structures. They help with interface adaptation, separation of concerns, and reducing duplication.
43+
44+
- Behavioral
45+
Patterns that focus on responsibilities, interactions between objects, and runtime algorithm variation. They aim to reduce coupling and improve testability.
46+
47+
## 1. Creational Patterns
48+
49+
Below are five representative creational patterns. For each I summarize the key idea, when to use it, and practical caveats.
50+
51+
### Singleton
52+
53+
|Item|Description|
54+
|:---|:---|
55+
|Key idea|Ensure a class has only one instance and provide global access to it.|
56+
|Pros|Centralizes access to shared resources.|
57+
|Cons|Can make testing hard due to lifecycle/global state. Consider dependency injection as an alternative.|
58+
59+
### Prototype
60+
61+
|Item|Description|
62+
|:---|:---|
63+
|Key idea|Create new objects by cloning existing instances.|
64+
|Pros|Reduces initialization cost via copying; useful for dynamic object creation.|
65+
|Cons|Be careful with deep vs. shallow copy and shared references.|
66+
67+
Use case: Cloning objects that have complex initialization.
68+
69+
### Factory Method
70+
71+
|Item|Description|
72+
|:---|:---|
73+
|Key idea|Provide a method for subclasses to decide which concrete class to instantiate.|
74+
|Pros|Makes it easy to extend how classes are created and lets clients depend on abstractions rather than concrete classes.|
75+
|Cons|Class hierarchies can grow when many concrete types are needed.|
76+
77+
### Abstract Factory
78+
79+
|Item|Description|
80+
|:---|:---|
81+
|Key idea|Provide an interface for creating families of related or dependent objects.|
82+
|Pros|Produce compatible sets of objects consistently; implementation swapping is easy.|
83+
|Cons|Adding new product types can require extensive changes across implementations.|
84+
85+
### Builder
86+
87+
|Item|Description|
88+
|:---|:---|
89+
|Key idea|Separate the construction of a complex object from its representation so the same construction process can create different representations.|
90+
|Pros|Enables readable construction code and staged configuration.|
91+
|Cons|Builder implementations can become complex if the construction process is complicated.|
92+
93+
Use case: Domain models with many optional parameters or multi-stage initialization.
94+
95+
## 2. Structural Patterns
96+
97+
Below are representative structural patterns, presented in the same format as the creational patterns.
98+
99+
### Adapter
100+
101+
|Item|Description|
102+
|:---|:---|
103+
|Key idea|Provide a wrapper that converts an existing class's interface into one expected by the client.|
104+
|Pros|Allows connecting legacy code or external libraries without modifying them.|
105+
|Cons|Too many adapters can reduce readability and increase maintenance cost.|
106+
107+
Use case: Adapting an old API to a new interface.
108+
109+
### Bridge
110+
111+
|Item|Description|
112+
|:---|:---|
113+
|Key idea|Separate an abstraction from its implementation so the two can vary independently.|
114+
|Pros|Makes it easy to switch or add implementations.|
115+
|Cons|Can introduce structural complexity; may be overengineering if not planned early.|
116+
117+
Use case: Decoupling platform-dependent implementations (e.g., switching rendering backends).
118+
119+
### Composite
120+
121+
|Item|Description|
122+
|:---|:---|
123+
|Key idea|Represent part-whole hierarchies so clients treat individual objects and compositions uniformly.|
124+
|Pros|Enables recursion-friendly structures and simplifies client code.|
125+
|Cons|Responsibilities between leaf and composite nodes can become unclear.|
126+
127+
Use case: Representing hierarchical UI components or file system structures.
128+
129+
### Decorator
130+
131+
|Item|Description|
132+
|:---|:---|
133+
|Key idea|Dynamically add responsibilities to an object. More flexible than subclassing for composition of behavior.|
134+
|Pros|Add behavior without modifying existing objects; combine decorators to build features.|
135+
|Cons|A large number of decorators can make debugging and tracing behavior harder.|
136+
137+
Use case: Chaining stream processing (e.g., compression, encryption).
138+
139+
### Facade
140+
141+
|Item|Description|
142+
|:---|:---|
143+
|Key idea|Provide a simplified, unified interface to a complex subsystem.|
144+
|Pros|Simplifies client usage and hides internal implementation details.|
145+
|Cons|Putting too much logic in the facade can bloat its responsibilities.|
146+
147+
Use case: Aggregating multiple APIs into a single service interface.
148+
149+
### Flyweight
150+
151+
|Item|Description|
152+
|:---|:---|
153+
|Key idea|Extract shared intrinsic state from many similar objects so that it can be shared; clients supply extrinsic state.|
154+
|Pros|Greatly reduces memory usage when many similar objects are needed.|
155+
|Cons|Managing shared vs. external state can be tricky.|
156+
157+
Use case: Text editors sharing font and glyph information across many character objects.
158+
159+
### Proxy
160+
161+
|Item|Description|
162+
|:---|:---|
163+
|Key idea|Provide a surrogate or placeholder for another object to control access, lazily initialize, or represent a remote object.|
164+
|Pros|Control access transparently and save resources via lazy loading.|
165+
|Cons|Adds overhead and can obscure the distinction between proxy and real object, complicating debugging.|
166+
167+
Use case: Lazy loading, remote stubs, or access control proxies.
168+
169+
Structural patterns increase indirection, so always weigh readability and runtime cost when applying them.
170+
171+
## 3. Behavioral Patterns
172+
173+
Below are representative behavioral patterns, summarized similarly.
174+
175+
### Chain of Responsibility
176+
177+
|Item|Description|
178+
|:---|:---|
179+
|Key idea|Chain multiple handlers and pass a request along the chain until a handler processes it.|
180+
|Pros|Reduces coupling between sender and receiver; makes adding or reordering handlers easy.|
181+
|Cons|Harder to trace which handler processed a request during debugging; be careful about requests that go unhandled.|
182+
183+
Use case: Logging frameworks or request filter chains.
184+
185+
### Command
186+
187+
|Item|Description|
188+
|:---|:---|
189+
|Key idea|Encapsulate an operation as an object.|
190+
|Pros|Abstracts actions, making it easier to parameterize, queue, or undo operations.|
191+
|Cons|Can add object overhead and complexity in simple cases.|
192+
193+
Use case: GUI actions with undo/redo support.
194+
195+
### Interpreter
196+
197+
|Item|Description|
198+
|:---|:---|
199+
|Key idea|Represent a grammar as an object structure and provide an interpreter to evaluate sentences in that grammar.|
200+
|Pros|Allows dynamic control of program behavior via external expressions.|
201+
|Cons|Can be hard to implement and maintain; performance may be a concern.|
202+
203+
Use case: Expression evaluators, small scripting languages, or domain-specific string formats.
204+
205+
### Iterator
206+
207+
|Item|Description|
208+
|:---|:---|
209+
|Key idea|Provide an abstraction for sequentially accessing elements of an aggregate without exposing its representation.|
210+
|Pros|Offers a consistent way to traverse different collection implementations.|
211+
|Cons|Requires careful design for concurrent modification during iteration.|
212+
213+
Use case: Collection traversal or stream processing.
214+
215+
### Mediator
216+
217+
|Item|Description|
218+
|:---|:---|
219+
|Key idea|Centralize complex interactions between many objects in a mediator to reduce direct dependencies.|
220+
|Pros|Simplifies individual classes and reduces coupling.|
221+
|Cons|Mediator can become complex and a maintenance bottleneck if overloaded.|
222+
223+
Use case: Coordinating UI component interactions or message dispatch in a chat room.
224+
225+
### Memento
226+
227+
|Item|Description|
228+
|:---|:---|
229+
|Key idea|Capture and externalize an object's internal state so it can be restored later without violating encapsulation.|
230+
|Pros|Allows state snapshots while preserving encapsulation.|
231+
|Cons|Copying/storing state can be costly; watch memory usage.|
232+
233+
Use case: Undo stacks in text editors.
234+
235+
### Observer (Publish-Subscribe)
236+
237+
|Item|Description|
238+
|:---|:---|
239+
|Key idea|Notify multiple registered objects when another object's state changes.|
240+
|Pros|Implements one-to-many notifications and achieves loose coupling.|
241+
|Cons|Be mindful of event order, thread-safety, and potential memory leaks from forgotten deregistration.|
242+
243+
Use case: Event-driven UIs and real-time subscription models.
244+
245+
### State
246+
247+
|Item|Description|
248+
|:---|:---|
249+
|Key idea|Delegate behavior to state objects based on an object's current state, making transitions explicit.|
250+
|Pros|Organizes complex conditional logic by state; improves clarity.|
251+
|Cons|Can produce many state classes; document sequences and relations for maintainability.|
252+
253+
Use case: Workflow engines or protocol state machines.
254+
255+
### Strategy
256+
257+
|Item|Description|
258+
|:---|:---|
259+
|Key idea|Encapsulate a family of algorithms and make them interchangeable at runtime.|
260+
|Pros|Enables independent testing and extension of algorithms; reduces conditional logic.|
261+
|Cons|May be over-abstraction for simple scenarios.|
262+
263+
Use case: Swappable sorting algorithms or payment calculation strategies.
264+
265+
### Template Method
266+
267+
|Item|Description|
268+
|:---|:---|
269+
|Key idea|Define the skeleton of an algorithm in a superclass, letting subclasses implement specific steps.|
270+
|Pros|Reuse common behavior while allowing variations in subclasses.|
271+
|Cons|Can increase coupling between subclasses and the superclass, reducing flexibility.|
272+
273+
Use case: Processing pipelines or sequences of operations with common steps.
274+
275+
### Visitor
276+
277+
|Item|Description|
278+
|:---|:---|
279+
|Key idea|Add new operations to object structures without changing the structures themselves.|
280+
|Pros|Makes adding new operations easy while keeping the object structure stable.|
281+
|Cons|Requires extending the element interfaces; structural changes to elements force visitor updates.|
282+
283+
Use case: Traversal-based analyses on abstract syntax trees (e.g., type checking or optimization).
284+
285+
## Practical caveats when adopting patterns
286+
287+
1. Think first whether the pattern is really needed
288+
If the problem doesn't match the pattern, don't introduce it. Simpler implementations are often sufficient.
289+
290+
2. Check whether language or framework features already provide an alternative
291+
Functional and dynamic languages can often express GoF patterns more succinctly or render some patterns unnecessary.
292+
293+
3. Prioritize testability and dependency management
294+
Be cautious with patterns that introduce global state or tight coupling.
295+
296+
4. Document your choices
297+
Record why a pattern was adopted in README/design docs. This helps future refactors and reviews.
298+
299+
5. Understand performance/maintenance trade-offs
300+
Indirection gives flexibility but can increase call overhead and cognitive load.
301+
302+
## Conclusion
303+
304+
GoF design patterns are powerful tools, but it's important to apply them appropriately rather than blindly. Understand each pattern's intent and consider language features and existing frameworks before adopting one.
305+
306+
Design depends on experience and context. Patterns expand your "design vocabulary" but are not an end in themselves. Start applying patterns in small, deliberate ways and share knowledge with your team.
307+
308+
(These days it's rare not to be familiar with these patterns, but still.)
309+
310+
Next time I'll explain detailed usage cases for several patterns with code examples.
File renamed without changes.

0 commit comments

Comments
 (0)