link: Design Patterns
Design Patterns Cheatsheet
Cheatsheet
Cheatsheet
Factory Method
Category: Creational.
What it is: Define an interface for creating an object, but let subclasses decide which class to instantiate. Lets a class defer instantiation to subclasses.
Description:
Summary
Cheat Sheet
Purpose:
- Simplifies object creation by allowing classes to delegate this responsibility to subclasses, thus providing flexibility in determining which objects to instantiate.
- Facilitates the addition of new product classes without altering existing code, by relying on inheritance and polymorphism.
Components:
- Creator (abstract class): An abstract class that declares the factory method, which returns an object of a
Product
type. This class also can define a default behavior of the factory method that returns a defaultProduct
object.- Concrete Creators: Subclasses of the
Creator
that override the factory method to return an instance of a specificProduct
.- Product (interface or abstract class): An interface or an abstract class which defines the products to be created.
- Concrete Products: Implementations of the
Product
interface or subclasses of theProduct
abstract class that define product objects to be created by the concrete creators.Usage:
- Define a
Product
interface or an abstract class to outline the structure of products.- Create concrete product classes that implement this interface or inherit from the abstract class.
- Develop a
Creator
abstract class with a method that returns objects of theProduct
type.- Implement concrete creator classes that extend the
Creator
class and override the factory method to create specific product instances.- Use the concrete creators to generate new product objects, allowing for dynamic changes in product instantiation based on the concrete creator class used.
Benefits:
- Increases the flexibility of systems by isolating the product creation code from the product use code.
- Supports the Open/Closed Principle by allowing the system to introduce new types of products without modifying existing client code.
- Encapsulates product knowledge into a single location, simplifying code maintenance and enhancing scalability.
Link to originalPersonal Thoughts
- When dealing with the creation of multiple products within our concrete factory and having only one dimension of products (e.g., WinButton, MacButton, LinuxButton), itâs feasible to utilize the Factory Method pattern effectively. Abstract Factory pattern might be overkill in this scenario.
- However, if we encounter situations where we have two dimensions of products, resulting in a multiplication of possibilities (e.g., WinButton, MacButton, LinuxButton, WinCheckbox, MacCheckbox, LinuxCheckbox), Abstract Factory pattern becomes more suitable. It provides a structured approach to handle the creation of related product families.
Abstract Factory
Category: Creational.
What it is: Provides an interface for creating families of related or dependent objects without specifying their concrete class.
Description:
Summary
Link to originalCheat Sheet
Purpose:
- Provides an interface for creating families of related or dependent objects without specifying their concrete classes.
- Allows the code to be independent of how its products are created, composed, and represented.
Components:
- Abstract Factory: An interface that declares a set of methods for creating each of the abstract products.
- Concrete Factory: Implements the abstract factory interface and returns products of a specific family.
- Abstract Products: A set of related products that belong to a product family.
- Concrete Products: Specific implementations of abstract products, grouped by variants.
- Client: Code that uses the abstract factory and the abstract products interfaces. It can work with any user-defined concrete factory/product variant.
Usage:
- Use when the system should be independent of how its products are created, composed, and represented.
- Use when the system needs to be configured with one of multiple families of products.
Benefits:
- Isolates concrete classes: The factory encapsulates the responsibility and the process of creating product objects.
- Promotes consistency among products: When products are designed to work together, a factory can ensure these products are compatible.
- Supports new kinds of products: Adding a new product family is easy because the abstract factory interface has fixed interfaces.
Common Scenarios:
- User interface kits where different operating systems require different visual appearances and behavior using the same abstract interface.
- Tools for working with various database platforms, each with specific configurations, behaviors, and appearances.
Builder
Category: Creational.
What it is: Separate the construction of a complex object from its representing so that the same construction process can create different representations.
Description:
Summary
Link to originalCheat Sheet
Purpose:
- Separates the construction of a complex object from its representation so that the same construction process can create different representations.
- Allows for fine control over the construction process.
Components:
- Director: Controls the construction process of an object using a builder instance.
- Builder: Provides an interface for adding parts to the objects being constructed.
- Concrete Builder: Implements the builder interface and provides an interface for retrieving the finished product.
- Product: The complex object being constructed.
Usage:
- Use when the algorithm for creating a complex object should be independent of the parts that make up the object and how theyâre assembled.
- Use when construction needs to allow different representations for the object thatâs constructed.
Benefits:
- Encapsulates code for construction and representation.
- Provides control over steps of the construction process.
- Supports varying the internal representation of products.
Common Scenarios:
- Creating complex composite objects that need to be constructed in various configurations.
- Generating different types of object representations under the same construction process.
Prototype
Category: Creational.
What it is: Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
Description:
Summary
Cheat Sheet
Purpose:
- Allows objects to be created by copying a prototypical instance, using cloning.
- Well-suited for scenarios where object creation is expensive and requires a lot of resources.
Components:
- Prototype: An interface that standardizes the cloning method.
- Concrete Prototype: Implements the cloning method to create duplicate objects.
- Client: Modifies the clone according to its needs.
Usage:
- Use when the classes to instantiate are specified at runtime, for instance, by dynamic loading.
- Use when avoiding building a class hierarchy of factories that parallels the class hierarchy of products.
- Use when instances of a class can have one of only a few different combinations of state.
Benefits:
- Adds and removes products dynamically.
- Specifies new objects by varying values.
- Reduces subclassing.
Common Scenarios:
- Implementing undo/redo operations where states are saved and restored.
- Generating complex, repeatable configurations on the fly.
Link to originalPersonal Thoughts
- Prototype patter can help us to copy even base private fields from object if they follow the same interface because we can pass our object to base constructor - ctor : base(obj)
- We can also have several methods of copy, for example Shallow Copy and Deep Copy
- We can merge Prototype and ConcretePrototype using abstract class with default implementation.
Singleton
Category: Creational.
What it is: Ensure a class only has one instance and provide a global point of access to it.
Description:
Summary
Cheat Sheet
Purpose:
- Ensures a class has only one instance, and provides a global point of access to it.
- Often used in cases where a single object is needed to coordinate actions across a system.
Components:
- Singleton: The class that is designed to have only one instance. It contains methods to allow clients to access the unique instance.
Usage:
- Use when exactly one instance of a class is required.
- Use to control client access to some shared resource.
Benefits:
- Provides a single point of access for a given instance.
- The instance is created only when needed.
Common Scenarios:
- Managing a connection to a database.
- Controlling the print spooler.
- Accessing a file system.
Link to originalPersonal Thoughts
The Singleton pattern is designed to ensure that a class has only one instance, not multiple instances. If thereâs a need to allow multiple instances, it deviates from the Singleton patternâs intended usage. In such cases, modifying the body of the
getInstance
method to accommodate multiple instances would be necessary.
Adapter
Category: Structural.
What it is: Convert the interface of a class into another interface clients expect. Lets classes work together that couldnât otherwise because of incompatible interfaces.
Description:
Summary
Link to originalCheat Sheet
Adapter Pattern Cheat Sheet Purpose:
- Allows objects with incompatible interfaces to collaborate.
- Often used to make existing classes work with others without modifying their source code.
Components:
- Target: The domain-specific interface that the client uses.
- Adapter: Adapts the interface of the Adaptee to the Target interface.
- Adaptee: The existing class that needs adapting.
- Client: Collaborates with objects conforming to the Target interface.
Usage:
- Use when you want to use an existing class, and its interface does not match the one you need.
- Use when you want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that donât necessarily share interfaces.
Benefits:
- Introduces only one object, and the adapterâs interface can be customized to work with the client.
- Increases transparency of operation.
- Provides a flexible solution to interface compatibility issues.
Common Scenarios:
- Integrating new components into existing systems where interfaces do not match.
- Converting data into various formats depending on user requirements.
Bridge
Category: Structural.
What it is: Decouple an abstraction from its implementation so that the two can vary independently.
Description:
Summary
Link to originalCheat Sheet
Bridge Pattern Cheat Sheet Purpose:
- Separates an objectâs interface from its implementation so that the two can vary independently.
- Promotes platform independence and extensibility.
Components:
- Abstraction: Defines the abstractionâs interface and maintains a reference to an object of the Implementor type.
- Refined Abstraction: Extends the interface defined by Abstraction.
- Implementor: Defines the interface for implementation classes. This interface doesnât have to correspond exactly to Abstractionâs interface; typically it provides primitive operations that the Abstraction defines in terms of.
- Concrete Implementor: Implements the Implementor interface and defines its concrete implementation.
Usage:
- Use when you want to avoid a permanent binding between an abstraction and its implementation. This might be the case, for example, when the implementation must be selected or switched at run-time.
- Use when both the abstractions and their implementations should be extensible by subclassing.
Benefits:
- Decouples an abstraction from its implementation so that the two can vary independently.
- Hides the implementation from the client completely.
- Increases the possibility to extend both the abstraction and the implementation independently.
Common Scenarios:
- Supporting multiple types of database servers.
- Creating a cross-platform GUI toolkit.
Composite
Category: Structural.
What it is: Compose objects into tree structures to represent part-whole hierarchies. Lets clients treat individual objects and compositions of objects uniformly.
Description:
Summary
Link to originalCheat Sheet
Composite Pattern Cheat Sheet Purpose:
- Allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
- Simplifies client code that has to deal with complex tree structures.
Components:
- Component: Declares the interface for objects in the composition and for accessing and managing its child components.
- Leaf: Represents leaf objects in the composition. A leaf has no children.
- Composite: Defines behavior for components having children and stores child components.
- Client: Manipulates objects in the composition through the Component interface.
Usage:
- Use when you want to represent part-whole hierarchies of objects.
- Use when you want clients to ignore the difference between compositions of objects and individual objects. Clients will treat all objects in the composite structure uniformly.
Benefits:
- Defines class hierarchies consisting of primitive objects and composite objects. Primitive objects can be composed into more complex objects, which in turn can be composed, and so on.
- Simplifies client code, as it can treat composite structures and individual objects uniformly.
- Makes it easier to add new kinds of components.
Common Scenarios:
- Graphic drawing editors where shapes can be composed into more complex shapes.
- User interface controls that have nested collections of other controls.
Decorator
Category: Structural.
What it is: Attach additional responsibilities to an object dynamically. Provide a flexible alternative to sub-classing for extending functionality.
Description:
Summary
Link to originalCheat Sheet
Decorator Pattern Cheat Sheet Purpose:
- Allows for the dynamic addition of behaviors to individual objects without affecting the behavior of other objects from the same class.
- Provides a flexible alternative to subclassing for extending functionality.
Components:
- Component: Defines the interface for objects that can have responsibilities added to them dynamically.
- ConcreteComponent: Defines an object to which additional responsibilities can be attached.
- Decorator: Maintains a reference to a Component object and defines an interface that conforms to Componentâs interface.
- ConcreteDecorator: Adds responsibilities to the component.
Usage:
- Use when you need to add functionalities to objects dynamically, and when subclassing would result in an exponential rise of new classes.
- Use to add or remove responsibilities from an object at runtime.
Benefits:
- More flexibility than static inheritance.
- Simplifies code maintenance because changes in behavior can be made by writing new code rather than altering existing code.
- Functions can be combined and extended independently.
Common Scenarios:
- UI components that must be decorated with additional graphical elements dynamically.
- Adding new operations to objects without altering their structure.
Facade
Category: Structural.
What it is: Provide a unified interface to a set of interfaces in a subsystem. Defines a high-level interface that makes the subsystem easier to use.
Description:
Summary
Link to originalCheat Sheet
Facade Pattern Cheat Sheet Purpose:
- Provides a simplified interface to a complex subsystem.
- Reduces the complexity of accessing a subsystem by providing a unified interface, making the subsystem easier to use.
Components:
- Facade: Provides a simple interface to the complex logic of one or more subsystems, while keeping the subsystems separate and managing their dependencies.
- Subsystems: Implements the subsystem functionality, which can be complex in nature. These operations are made available to the facade but hidden from the outside world.
Usage:
- Use when you want to provide a simple or reduced interface to a complex subsystem.
- Use to divide a system into subsystems and reduce dependencies between clients and subsystems.
Benefits:
- Isolates clients from subsystem components, reducing the number of objects that clients deal with and making the subsystem easier to use and maintain.
- Promotes weak coupling between the subsystem and its clients.
- Often used in layered architectures to bring all complex dependencies into one place.
Common Scenarios:
- Libraries and frameworks that require a complex set of configurations can provide a simplified API to improve user experience.
- Systems where the division into layers provides a clear distinction between components.
Flyweight
Category: Structural.
What it is: Use sharing to support large numbers of fine grained objects efficiently.
Description:
Summary
Link to originalCheat Sheet
Flyweight Pattern Cheat Sheet Purpose:
- Reduces the cost of creating and manipulating a large number of similar objects.
- Saves memory by sharing as much data as possible with other similar objects (intrinsic state).
Components:
- Flyweight: Interface through which flyweights can receive and act on extrinsic states.
- ConcreteFlyweight: Implements the Flyweight interface and stores intrinsic state. These objects must be sharable.
- FlyweightFactory: Creates and manages flyweight objects and ensures that flyweights are shared properly. When a client requests a flyweight, the factory either uses an existing instance or creates a new one.
- Client: Maintains the extrinsic state and passes it to the flyweight objects for processing.
Usage:
- Use when there are many instances of objects that are similar in structure but vary in state.
- Use when reducing memory footprint is a priority.
Benefits:
- Greatly reduces the number of objects that need to be created, reducing memory usage and increasing application performance.
- Centralizes state management in shared objects, simplifying data management across the system.
Common Scenarios:
- Character objects in word processors.
- Tree and forest simulations where many trees share the same data (species, textures).
Proxy
Category: Structural.
What it is: Provide a surrogate or placeholder for another object to control access to it.
Description:
Summary
Link to originalCheat Sheet
Proxy Pattern Cheat Sheet Purpose:
- Provides a surrogate or placeholder for another object to control access to it.
- Useful for managing costly operations, adding security measures, or providing a simpler interface to complex systems.
Components:
- Subject Interface: Defines the common interface for the real object and the proxy, ensuring that a proxy can be used in place of the real object.
- Real Subject: The actual object that performs the real operations the proxy represents.
- Proxy: Acts as an intermediary for the real subject, implementing the same interface, and controls access to it.
- Client: Interacts with the Proxy instead of the direct real subject.
Usage:
- Use when you need to control the creation and access to an object without clients knowing the implementation details.
- Use for lazy initialization, logging, access control, or to add other administrative functions transparently.
Benefits:
- Provides a layer of security by serving as a gatekeeper to the real subject.
- Can manage the lifecycle of the real subject without the clientâs knowledge.
- Reduces system complexity by controlling operations like creating and deleting objects or managing resource-intensive operations.
Common Scenarios:
- Virtual Proxies that delay object creation until necessary.
- Protection Proxies that control access to sensitive objects.
- Remote Proxies that encapsulate access to remote objects as if they were local.
Chain Of Responsibility
Category: Behavioral.
What it is: Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.
Description:
Summary
Link to originalCheat Sheet
Chain of Responsibility Pattern Cheat Sheet Purpose:
- Allows passing a request along a chain of handlers until one of them handles the request.
- Decouples the sender of a request from its receivers by giving multiple objects a chance to handle the request.
Components:
- Handler Interface: Defines an interface for handling requests and optionally implementing the successor link.
- Concrete Handler: Handles requests they are responsible for; otherwise, forwards the request to the next handler in the chain.
- Client: Initiates the request to a Concrete Handler object on the chain.
Usage:
- Use when more than one object may handle a request, and the handler isnât known in advance.
- Use when the set of handlers should be specified dynamically.
Benefits:
- Reduces coupling since it frees an object from having to know which other object handles a request.
- Adds flexibility in assigning responsibilities to objects.
- Allows a set of classes to act as one with each class handling the request if they are capable.
Common Scenarios:
- Event handling systems where events might be handled at multiple stages.
- Approval processes where a request passes through a chain of authority to get approved.
Command
Category: Behavioral.
What it is: Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
Description:
Summary
Link to originalCheat Sheet
Command Pattern Cheat Sheet Purpose:
- Encapsulates a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
Components:
- Command Interface: Declares an interface for executing operations.
- Concrete Command: Implements the Command interface and defines a binding between a Receiver object and an action.
- Invoker: Asks the command to carry out the request.
- Receiver: Knows how to perform the operations associated with carrying out a request.
- Client: Creates a Concrete Command object and sets its receiver.
Usage:
- Use when you need to issue requests to objects without knowing anything about the operation being requested or the receiver of the request.
- Use to implement reversible operations.
Benefits:
- Decouples the class that invokes the operation from the one that knows how to perform it.
- Commands can be extended and replaced.
- You can assemble sets of commands into composite commands.
Common Scenarios:
- GUI buttons and menu items in software development frameworks.
- Operations in database transaction systems that support rollback.
- Macro recording and management.
Iterator
Category: Behavioral.
What it is: Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
Description:
Summary
Link to originalCheat Sheet
Iterator Pattern Cheat Sheet Purpose:
- Provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
- Facilitates the traversal of a collection of objects without the complexities of understanding and interacting with its internal structure.
Components:
- Iterator Interface: Defines an interface for accessing and traversing elements.
- Concrete Iterator: Implements the Iterator interface and keeps track of the current position in the traversal of the aggregate.
- Aggregate Interface: Defines an interface for creating an Iterator object.
- Concrete Aggregate: Implements the Aggregate interface and returns an instance of the corresponding Concrete Iterator.
Usage:
- Use when you want to hide the complexities of the internal structure of an aggregate object from its clients.
- Use to support multiple simultaneous traversals of aggregate objects.
- Use to provide a uniform interface for traversing different aggregate structures (e.g., trees, graphs, and lists).
Benefits:
- Supports variations in the traversal of an aggregate.
- Minimizes the duplication of traversal code.
- Decouples the collection from its traversal process.
Common Scenarios:
- Navigating through a complex data structure like a linked list or a binary tree.
- Implementing polymorphic collections and iterators that allow handling of different data structures through a uniform interface.
Mediator
Category: Behavioral.
What it is: Define an object that encapsulates how a set of objects interact. Promotes loose coupling by keeping objects from referring to each other explicitly and it lets you vary their interactions independently.
Description:
Summary
Link to originalCheat Sheet
Mediator Pattern Cheat Sheet Purpose:
- Defines an object that encapsulates how a set of objects interact.
- Promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
Components:
- Mediator Interface: Defines the interface for communication between Colleague objects.
- Concrete Mediator: Implements the Mediator interface and coordinates communication between Colleague objects. It knows and maintains its colleagues.
- Colleague Classes: Each Colleague class knows its Mediator object. It communicates with its mediator whenever it would have otherwise communicated with another colleague.
Usage:
- Use when a set of objects communicate in well-defined but complex ways that are hard to manage or understand.
- Use to centralize complex communications and control logic between related objects.
Benefits:
- Reduces subclassing by centralizing control logic.
- Decouples colleagues which leads to fewer, more manageable dependencies.
- Simplifies maintenance of the application by centralizing control logic.
Common Scenarios:
- User interface designs where multiple components need to interact, but itâs undesirable for them to have direct references to each other.
- Distributed systems where multiple services interact, and central control of these interactions is required.
Memento
Category: Behavioral.
What it is: Without violating encapsulation, capture and externalize an objectâs internal state so that the object can be restored to this state later.
Description:
Summary
Link to originalCheat Sheet
Memento Pattern Cheat Sheet Purpose:
- Allows an object to save its internal state without exposing its internal structure, so that it can be restored to this state later.
- Useful for implementing undo mechanisms in applications.
Components:
- Originator: The object that knows how to save itself. It creates a memento containing a snapshot of its current internal state.
- Memento: A small object used by the Originator to store its internal state. Memento restricts other objects from accessing this state, enforcing encapsulation.
- Caretaker: Holds onto the Memento. It can request a Memento from the Originator to capture the current state and pass it back at a later date for undo functionality. The caretaker is responsible for keeping the memento.
Usage:
- Use when you need to restore an object back to its previous state (undo via rollback).
- Use when a direct interface to obtain the state would expose implementation details and break the objectâs encapsulation.
Benefits:
- Provides a clean way to recover state for an object or an application.
- Does not violate the encapsulation of the Originator.
- Decouples the Originatorâs state management from the main functionality, focusing on doing one thing well.
Common Scenarios:
- Implementing undo in software, allowing users to revert to a previous state.
- Saving snapshots of an objectâs state for recovery processes.
Observer
Category: Behavioral.
What it is: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
Description:
Summary
Link to originalCheat Sheet
Observer Pattern Cheat Sheet Purpose:
- Allows a subject to notify a list of observers (subscribers) automatically of any state changes, usually by calling one of their methods.
- Facilitates low coupling between a subject and its observers.
Components:
- Subject: Maintains a list of observers, facilitates adding or removing observers, and notifies them of state changes.
- Observer Interface: Provides a method signature (
update
) that observers must implement in order to receive updates from the subject.- Concrete Observer: Implements the Observer interface to keep its state consistent with that of the subject. Performs actual update actions in response to notifications.
Usage:
- Use when changes to one object require changing others, and the number of objects involved is unknown or changes dynamically.
- Use to promote a loosely coupled system where interacting components remain independent.
Benefits:
- Promotes the principle of separation of concerns.
- Supports broadcast communication which is not feasible using other methods.
- Observers are only loosely coupled to the subject: minimal interface requirements.
Common Scenarios:
- Implementing distributed event-handling systems.
- In MVC architecture, model updates are often notified to multiple views using an Observer pattern.
- Real-time data feeds that need to be updated in the UI or elsewhere when data changes.
State
Category: Behavioral.
What it is: Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
Description:
Summary
Link to originalCheat Sheet
State Pattern Cheat Sheet Purpose:
- Allows an object to alter its behavior when its internal state changes, appearing as if it changed its class.
- Encapsulates varying behavior for the same routine based on an objectâs state object.
Components:
- Context: Maintains an instance of a ConcreteState subclass that defines the current state.
- State Interface: Defines an interface to encapsulate the behavior associated with a particular state of the Context.
- Concrete States: Implement the State interface and provide the behavior associated with a state of the Context.
Usage:
- Use when the behavior of an object should change at runtime depending on its state.
- Use when complex conditions tie object behavior to its state, and many operations within the object conditional statements that depend on the objectâs state.
Benefits:
- Organizes state-specific code into separate classes.
- Introduces new states without changing existing state classes or the context.
- Simplifies the code in the context required to switch between states.
Common Scenarios:
- Workflow management where objects go through different states with different transition rules.
- UI tools where user interactions change the state of objects, affecting behavior and operations.
Strategy
Category: Behavioral.
What it is: Define a family of algorithms, encapsulate each one, and make them interchangeable. Lets the algorithm vary independently from clients that use it.
Description:
Summary
Link to originalCheat Sheet
Strategy Pattern Cheat Sheet Purpose:
- Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
- Offers a way to define a group of behaviors or algorithms and make them interchangeable within that family.
Components:
- Context: Maintains a reference to one of the concrete strategies and communicates with this object only via the strategy interface.
- Strategy Interface: Common interface for all strategies that declares a method the context uses to call the algorithm defined by a Concrete Strategy.
- Concrete Strategies: Implement different variations of an algorithm the Strategy interface defines.
Usage:
- Use when different variations of an algorithm are needed.
- Use when algorithm uses data clients shouldnât know about. Hide complex, algorithm-related data structures behind an interface.
- Use to replace conditional statements related to various behaviors packed into one class.
Benefits:
- A family of algorithms can be easily switched at runtime (interchangeability).
- Encapsulation of algorithm and implementation details.
- Adding new strategies or modifying existing ones does not disturb the host context.
Common Scenarios:
- Data validation processes that use various algorithms based on the nature of data being validated.
- Different user interface behaviors under various configurations or environments.
- Resource negotiation algorithms that vary depending on system load and network conditions.
Template Method
Category: Behavioral.
What it is: Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Lets subclasses redefine certain steps of an algorithm without changing the algorithmâs structure.
Description:
Summary
Link to originalCheat Sheet
Template Method Pattern Cheat Sheet Purpose:
- Defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure.
- Allows redefining certain steps of an algorithm without changing the algorithmâs structure.
Components:
- Abstract Class: Defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm.
- Concrete Class: Implements the primitive operations to carry out subclass-specific steps of the algorithm.
Usage:
- Use when you want to let clients extend only particular steps of an algorithm, but not the algorithmâs structure.
- Use when you have several classes that contain nearly identical algorithms with some minor differences in the sequence of steps.
Benefits:
- Facilitates code reuse and avoids duplication in subclasses.
- Offers a clear template for an algorithm sequence, ensuring consistency.
- Simplifies maintenance as changes to the algorithmâs structure require modifications only in the abstract class, not in each subclass.
Common Scenarios:
- Data processing frameworks where the steps to process data are the same, but the actual processing differs based on the data format.
- Games or applications that need to extend the frameworkâs algorithm while keeping the outline the same.
Visitor
Category: Behavioral.
What it is: Represent an operation to be performed on the elements of an object structure. Lets you define a new operation without changing the classes of the elements on which it operates.
Description:
Summary
Link to originalCheat Sheet
Visitor Pattern Cheat Sheet Purpose:
- Lets you define a new operation without changing the classes of the elements on which it operates.
- Useful for operations over complex object structures, like walking a tree structure and performing operations on each node.
Components:
- Visitor Interface: Declares a visit operation for each class of Concrete Element in the object structure. The operationâs name and signature identifies the class that sends the visit request to the visitor.
- Concrete Visitor: Implements each operation declared by Visitor, which forms the algorithm that is applied to all elements.
- Element Interface: Defines an
accept
method that takes a visitor as an argument.- Concrete Element: Implements the
accept
method defined by Element, which typically calls the visit method on the Visitor, allowing the Visitor to define the operation executed on the element.- Object Structure: A collection of Elements able to enumerate its elements and provide a high-level interface for allowing the visitor to visit its elements.
Usage:
- Use when you need to perform operations across a complex object structure and need to avoid âpollutingâ their classes with operation-specific code.
- Use when you anticipate many distinct and unrelated operations on objects in an object structure that donât warrant changing object classes.
Benefits:
- Adds new operations easily by adding new visitor classes.
- Keeps related operations together, making them easier to extend and maintain.
- Separates unrelated operations, keeping the classes that define the object structure clean and unchanged.
Common Scenarios:
- Document object models where operations like rendering, syntax checking, and type checking must be performed.
- GUI frameworks where actions can be applied to various elements without changing the element classes themselves.