Creational Patterns
-
Singleton Pattern: Ensures that a class has only one instance and provides a global access point to it.
- Usage Scenarios: Suitable for resource management (such as database connection pools, thread pool management), shared resource access (logging, configuration management), global state management (user session management, cache management), etc.
- Related Applications: In Java, the
<span>java.lang.Runtime</span>class is an application of the Singleton pattern, which provides the unique instance of the current runtime through the<span>getRuntime()</span>method, used to manage the runtime environment of the Java Virtual Machine; in database connection management, a singleton database connection pool is created to avoid performance loss caused by frequent creation and destruction of connections. -
Factory Method Pattern: Defines an interface for creating objects, but allows subclasses to decide which class to instantiate, separating the creation and use of objects.
- Usage Scenarios: Applicable when the logic for creating objects frequently changes, or when different types of objects need to be created based on different conditions.
- Related Applications: In the Spring framework, the
<span>BeanFactory</span>is an application of the Factory Method pattern, used to create and manage Bean objects; in game development, different types of enemy objects are created based on the requirements of different levels. -
Abstract Factory Pattern: Provides an interface for creating families of related or dependent objects without specifying their concrete classes.
- Usage Scenarios: Suitable for creating families of objects that are related, and when the system needs to be independent of how these objects are created, composed, and represented.
- Related Applications: In graphical user interface libraries, creating families of component objects such as windows and buttons in different operating system styles (e.g., Windows style, Mac style); in database access layers, creating corresponding connection objects and statement objects for different databases (e.g., MySQL, Oracle).
-
Builder Pattern: Separates the construction of a complex object from its representation, allowing the same construction process to create different representations.
- Usage Scenarios: When the algorithm for creating a complex object should be independent of the parts that make up the object and how they are assembled; or when the process of creating an object requires many steps, and the order of these steps may vary.
- Related Applications: In automobile manufacturing, a fixed assembly process can produce different models such as sedans and SUVs through different configuration combinations; constructing complex SQL query statements by adding query conditions and sorting rules step by step.
-
Prototype Pattern: Specifies the kind of objects to create using a prototypical instance, and creates new objects by copying this prototype.
- Usage Scenarios: When the cost of creating an object is high (e.g., initializing an object consumes a lot of resources), or when multiple similar objects need to be created dynamically at runtime.
- Related Applications: In games, character creation can be done by copying existing character prototypes and modifying some attributes (e.g., equipment, level) to quickly generate new characters; in graphic design software, copying graphic elements.
Structural Patterns
-
Adapter Pattern: Converts the interface of a class into another interface that clients expect, allowing classes that cannot work together due to incompatible interfaces to work together.
- Usage Scenarios: When the system needs to use an existing class whose interface does not meet the system’s needs; or when a reusable class needs to work with classes that do not necessarily conform to some interfaces.
- Related Applications: In Java, the JDBC interface uses the Adapter pattern to allow Java programs to access different types of databases; adapting American appliances (110V) to work with Chinese 220V voltage through an adapter.
-
Decorator Pattern: Dynamically adds responsibilities to an object without modifying its structure, allowing for additional functionality.
- Usage Scenarios: When there is a need to dynamically add functionality to an object at runtime, and these functionalities can be combined, or when one does not want to extend class functionality through inheritance (to avoid too many subclasses).
- Related Applications: In Java’s I/O streams,
<span>BufferedInputStream</span>,<span>DataInputStream</span>, etc., are decorator classes used to add buffering, data processing, and other functionalities to basic input streams; dynamically adding temporary attribute enhancement effects to game characters, such as increased attack power and defense bonuses. -
Proxy Pattern: Provides a surrogate or placeholder for another object to control access to it.
- Usage Scenarios: Remote proxies (accessing remote objects, such as remote service calls), virtual proxies (lazy loading, such as displaying a placeholder while loading a large image, and loading the image when accessed), protection proxies (controlling access permissions to objects, such as permission control), etc.
- Related Applications: In Spring AOP, the Proxy pattern is used to implement aspect-oriented programming; in web applications, accessing the internet through a proxy server, which can implement caching, filtering, and other functionalities.
-
Facade Pattern: Provides a unified high-level interface to a set of interfaces in a subsystem, making the subsystem easier to use.
- Usage Scenarios: When the subsystem is complex, with many interacting classes and interfaces, and the client only needs to call the subsystem’s functions simply.
- Related Applications: In home theater systems, controlling multiple devices such as projectors, sound systems, and DVD players through a single remote control (facade interface); in e-commerce systems, encapsulating complex business logic such as product queries, inventory checks, and order creation into a simple ordering interface for clients.
-
Composite Pattern: Composes objects into tree structures to represent part-whole hierarchies, allowing users to treat individual objects and compositions uniformly.
- Usage Scenarios: When there is a part-whole hierarchy relationship in the problem space, and one wishes to handle individual objects and composite objects uniformly.
- Related Applications: In operating system file and folder management, folders can contain files and subfolders, allowing unified operations (such as copy, delete) on files and folders; in graphic editing software, graphics can consist of simple shapes (like lines, circles) and composite shapes (composed of multiple simple shapes), allowing unified operations such as drawing and moving.
-
Flyweight Pattern: Uses sharing to effectively support large numbers of fine-grained objects.
- Usage Scenarios: When there are many similar objects in the system, and the cost of creating and destroying these objects is high, while the internal state of the objects can be shared.
- Related Applications: In text editing software, character objects can be shared, with the same character at different positions using the same object instance; in game development, a large number of identical game items (such as coins, bullets) can use the Flyweight pattern to reduce memory usage.
-
Bridge Pattern: Separates the abstraction from its implementation so that both can vary independently.
- Usage Scenarios: When a class has two independent dimensions that can change, and both dimensions need to be extended.
- Related Applications: In graphic rendering systems, separating graphic types (such as circles, squares) from rendering methods (such as vector rendering, raster rendering); in payment systems, separating payment methods (such as Alipay, WeChat Pay) from payment channels (such as domestic payments, cross-border payments).
Behavioral Patterns
-
Strategy Pattern: Defines a family of algorithms, encapsulates each one, and makes them interchangeable, allowing the algorithm’s changes to not affect the clients that use them.
- Usage Scenarios: When a system has many different algorithms or behaviors that can be interchanged in different situations.
- Related Applications: In e-commerce systems, different promotional strategies (such as discounts, full reductions, gifts) can be implemented using the Strategy pattern; in games, different attack behaviors of characters (such as melee attacks, ranged attacks) can be encapsulated into different strategy classes.
-
Template Method Pattern: Defines the skeleton of an algorithm in an operation, deferring some steps to subclasses, allowing subclasses to redefine certain specific steps of the algorithm without changing its structure.
- Usage Scenarios: When multiple subclasses have common behaviors that can be abstracted into a template, while each subclass has its specific implementation steps.
- Related Applications: In the Junit testing framework, the execution flow of test cases (such as initialization, executing test methods, cleanup) is a fixed template, while different test methods are specific implementation steps; in file reading operations, opening files, reading data, and closing files are fixed processes, while the reading methods for different file types are specific steps.
-
Command Pattern: Encapsulates a request as an object, allowing parameterization of clients with different requests, queuing requests, logging requests, and supporting undoable operations.
- Usage Scenarios: When there is a need to decouple the sender and receiver of a request, or when supporting undo, redo, queuing, and other functionalities is required.
- Related Applications: In graphic editing software, operations on graphics (such as drawing, moving, deleting) can be encapsulated as command objects, supporting undo and redo operations; in games, player actions (such as attacking, jumping) can be encapsulated as command objects, facilitating operation recording and playback functionalities.
-
Chain of Responsibility Pattern: Allows multiple objects to handle a request, avoiding coupling between the sender and receiver of the request, linking these objects into a chain, and passing the request along the chain until one object handles it.
- Usage Scenarios: When the processing of a request requires multiple objects to handle it sequentially, and the collection of processing objects can be dynamically specified, or when the processing flow of the request is uncertain and may change.
- Related Applications: In approval processes, a leave application may need to be approved sequentially by a team leader, department manager, and general manager, with each approver deciding whether to approve or continue passing it along; in Java’s exception handling, exceptions can propagate up the call stack until they are caught and handled.
-
Iterator Pattern: Provides a way to sequentially access the elements of an aggregate object without exposing its internal representation.
- Usage Scenarios: When there is a need to traverse aggregate objects (such as collections, arrays) and the traversal method should be decoupled from the internal implementation of the aggregate object.
- Related Applications: In Java, implementations of the
<span>Collection</span>interface (such as<span>ArrayList</span>,<span>HashSet</span>) provide an<span>Iterator</span>for traversing collection elements; the iterator pattern can also be used in traversing database query result sets. -
Mediator Pattern: Encapsulates a set of object interactions in a mediator object, allowing objects to interact without explicitly referencing each other, thus reducing coupling and allowing independent changes to their interactions.
- Usage Scenarios: When the interaction relationships between objects are complex, forming a web structure that makes maintenance and extension difficult.
- Related Applications: In graphical user interface design, interactions between multiple components (such as buttons, text boxes, list boxes) can be managed by a mediator (such as a window class); in airport scheduling systems, interactions between planes, control towers, runways, etc., can be coordinated through an airport scheduling center (mediator).
-
Memento Pattern: Captures an object’s internal state without violating encapsulation, and saves this state outside the object, allowing the object to be restored to its previously saved state later.
- Usage Scenarios: When it is necessary to save the historical state of an object for later restoration to a certain historical state, such as in undo operations, version control, etc.
- Related Applications: In text editors, saving and restoring the historical versions of text; in games, saving and loading game progress.
-
Interpreter Pattern: Given a language, defines a representation of its grammar and an interpreter that uses this representation to interpret sentences in the language.
- Usage Scenarios: When there is a language that needs to be interpreted and sentences in that language can be represented as an abstract syntax tree.
- Related Applications: Regular expression engines are an application of the interpreter pattern, used to interpret and match regular expressions; in parsing database query languages (such as SQL), the interpreter pattern can also be used.
-
Visitor Pattern: Represents an operation to be performed on elements of an object structure, allowing new operations to be defined on these elements without changing their classes.
- Usage Scenarios: When there are multiple types of elements in an object structure, and different operations need to be performed on these elements while decoupling the operations from the elements.
- Related Applications: In compiler design, performing semantic analysis, code generation, and other operations on different nodes (such as expression nodes, statement nodes) in an abstract syntax tree; in graphic editing software, performing unified operations (such as area calculation, drawing) on different types of graphics (such as lines, circles, rectangles).
Other Patterns
-
Filter Pattern: Allows developers to filter a set of objects using different criteria, connecting them in a decoupled manner through logical operations.
- Usage Scenarios: In data processing, filtering data sets based on different conditions; in file systems, filtering files based on file names, file types, file sizes, etc.
- Related Applications: In e-commerce systems, filtering product lists based on price, brand, category, etc.; in logging systems, filtering log records based on log levels, time, etc.
-
Object Pool Pattern: Creates an object pool to manage the creation and destruction of objects, obtaining objects from the pool when needed and returning them after use, rather than frequently creating and destroying objects.
- Usage Scenarios: Suitable for objects with high creation and destruction costs, such as database connections, threads, network connections, etc.
- Related Applications: Database connection pool technologies, such as C3P0 and Druid, manage the creation, allocation, and recycling of database connections; thread pools, such as
<span>ThreadPoolExecutor</span>in Java, manage the creation and reuse of threads. -
Callback Pattern: A common design pattern that allows one function to call another after completing its task, often used in asynchronous operations.
- Usage Scenarios: In asynchronous I/O operations, event handling, multithreaded programming, etc., when some follow-up operations need to be executed after a task is completed.
- Related Applications: In JavaScript, asynchronous operations (such as
<span>setTimeout</span>,<span>AJAX requests</span>) handle results through callback functions after completion; in Java, asynchronous tasks can be implemented through<span>Future</span>and<span>Callable</span>, with a callback mechanism to obtain task execution results. -
MVC Pattern: Divides a software system into three basic parts: Model, View, and Controller, used to separate data representation, data processing, and user interaction.
- Usage Scenarios: Suitable for developing interactive web applications, desktop applications, etc., making the code structure clearer and easier to maintain and extend.
- Related Applications: In Java web development, frameworks like Spring MVC and Struts are based on the MVC pattern; in iOS and Android mobile application development, the MVC pattern is also widely used to organize code structure.