Skip to content

yaroslav-android/DesignPatternsSamples

Repository files navigation

Design Patterns Cheat Sheet

Table of contents (23)

Note: Patterns with [x] mark excluded from code samples due to simplicity or specific nature of the implementation.

Creational Patterns

Abstract Factory

  • Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
  • Use Case: In a game development framework, an abstract factory can create families of related objects such as characters, weapons, and enemies for different game levels or scenarios.
  • Benefits:
    • Encapsulates object creation.
    • Promotes consistency within families of objects.
  • Liabilities:
    • Can become complex when adding new product variations or families.
  • Related Patterns: Factory Method, Prototype, Singleton.

Factory Method

  • Intent: Define an interface for creating objects, but let subclasses decide which class to instantiate.
  • Use Case: In a logging library, a factory method can create different logger instances (e.g., file logger, console logger, database logger) based on configuration or runtime conditions.
  • Benefits:
    • Provides a hook for subclasses to create objects.
    • Supports polymorphism.
  • Liabilities:
    • Can lead to subclass proliferation.
  • Related Patterns: Abstract Factory, Prototype, Template Method.

Builder

  • Intent: Separate the construction of a complex object from its representation so that the same construction process can create different representations.
  • Use Case: In a web application framework, a builder pattern can be used to construct complex HTML documents or database queries dynamically based on user input or configuration.
  • Benefits:
    • Separates object construction from representation.
    • Supports different representations.
  • Liabilities:
    • Requires more code due to additional builder classes.
  • Related Patterns: Abstract Factory, Composite.

Prototype

  • Intent: Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
  • Use Case: In a document management system, a prototype pattern can be used to clone existing documents or templates to create new documents with similar structures and contents.
  • Benefits:
    • Allows for cloning of objects.
    • Reduces subclassing.
  • Liabilities:
    • Can be inefficient for complex objects with circular references.
  • Related Patterns: Abstract Factory, Composite, Decorator.

Singleton

  • Intent: Ensure a class has only one instance and provide a global point of access to that instance.
  • Use Case: In a configuration manager, a singleton pattern can ensure that there is only one instance of the configuration object throughout the application, allowing global access to configuration settings.
  • Benefits:
    • Ensures only one instance of a class.
    • Provides global access.
  • Liabilities:
    • Can introduce global state.
    • Difficult to unit test.
  • Related Patterns: Abstract Factory, Builder, Prototype.

Structural Patterns

Adapter

  • Intent: Convert the interface of a class into another interface clients expect. Allows classes with incompatible interfaces to work together.
  • Use Case: In a legacy code integration project, an adapter pattern can adapt existing interfaces or APIs to work with modern libraries or frameworks, facilitating interoperability between different systems.
  • Benefits:
    • Allows classes with incompatible interfaces to work together.
  • Liabilities:
    • Can lead to a complex system with many adapters.
  • Related Patterns: Bridge, Decorator, Proxy.

Bridge

  • Intent: Decouple an abstraction from its implementation so that the two can vary independently.
  • Use Case: In a graphics rendering engine, a bridge pattern can decouple the abstraction of drawing shapes from their implementations, allowing the engine to support different rendering backends (e.g., OpenGL, DirectX).
  • Benefits:
    • Decouples abstraction from implementation.
    • Allows for independent evolution.
  • Liabilities:
    • Can lead to a proliferation of classes.
  • Related Patterns: Abstract Factory, Adapter.

Composite

  • Intent: Compose objects into tree structures to represent part-whole hierarchies. Clients can treat individual objects and compositions of objects uniformly.
  • Use Case: In a file system application, a composite pattern can represent directories and files as a tree structure, allowing users to perform operations (e.g., copy, delete) on both individual files and entire directories.
  • Benefits:
    • Treats individual objects and compositions uniformly.
    • Simplifies client code.
  • Liabilities:
    • Can be difficult to restrict the types of components.
  • Related Patterns: Chain of Responsibility, Decorator, Flyweight, Iterator, Visitor.

Decorator

  • Intent: Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
  • Use Case: In a text processing library, a decorator pattern can add formatting or encryption capabilities to streams or files, allowing users to apply multiple transformations to data streams.
  • Benefits:
    • Allows for adding behavior dynamically.
    • Promotes single responsibility.
  • Liabilities:
    • Can lead to a large number of small classes.
  • Related Patterns: Adapter, Composite, Strategy.

Facade

  • Intent: Provide a unified interface to a set of interfaces in a subsystem. Simplifies a complex system by providing a higher-level interface.
  • Use Case: In a customer relationship management (CRM) system, a facade pattern can provide a simplified interface for managing complex business processes such as customer accounts, orders, and invoices.
  • Benefits:
    • Simplifies complex systems.
    • Provides a unified interface.
  • Liabilities:
    • Can become a monolithic interface.
    • Hides complexity.
  • Related Patterns: Abstract Factory, Mediator.

Flyweight

  • Intent: Use sharing to support large numbers of fine-grained objects efficiently.
  • Use Case: In a graphical user interface (GUI) framework, a flyweight pattern can optimize memory usage by sharing common resources (e.g., fonts, icons) among multiple UI components.
  • Benefits:
    • Reduces memory usage by sharing state.
    • Supports large numbers of objects.
  • Liabilities:
    • Can introduce synchronization overhead.
    • Reduces encapsulation.
  • Related Patterns: Composite, State, Strategy.

Proxy

  • Intent: Provide a surrogate or placeholder for another object to control access to it.
  • Use Case: In a remote service client, a proxy pattern can provide a local representation of a remote service interface, allowing clients to interact with the service transparently without needing to know its location or implementation details.
  • Benefits:
    • Controls access to an object.
    • Adds functionality transparently.
  • Liabilities:
    • Can introduce overhead.
    • Can complicate the system.
  • Related Patterns: Adapter, Decorator.

Behavioral Patterns

Chain of Responsibility

  • Intent: 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 it is handled.
  • Use Case: In a request processing pipeline, a chain of responsibility pattern can handle incoming requests by passing them through a series of handlers, each responsible for processing specific types of requests.
  • Benefits:
    • Allows for flexible processing of requests.
    • Reduces coupling.
  • Liabilities:
    • Can result in unhandled requests.
    • Can be difficult to debug.
  • Related Patterns: Composite.

Command

  • Intent: Encapsulate a request as an object, thereby allowing for parameterization of clients with queues, requests, and operations.
  • Use Case: In a text editor application, a command pattern can encapsulate user actions (e.g., typing, deleting, formatting) as objects, allowing for undo/redo functionality and macro recording.
  • Benefits:
    • Encapsulates requests as objects.
    • Supports undo/redo operations.
  • Liabilities:
    • Can lead to a large number of command classes.
    • Can be complex to implement.
  • Related Patterns: Composite, Memento.

Interpreter

  • Intent: Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
  • Use Case: In a query language interpreter, an interpreter pattern can parse and evaluate queries expressed in a domain-specific language, converting them into executable commands or SQL statements.
  • Benefits:
    • Represents language grammar and interprets sentences.
    • Supports extensibility.
  • Liabilities:
    • Can be difficult to maintain.
    • Performance overhead.
  • Related Patterns: Composite, Flyweight, Iterator, Visitor.

Iterator

  • Intent: Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
  • Use Case: In a collection library, an iterator pattern can provide a uniform way to traverse different types of collections (e.g., arrays, lists, trees) without exposing their internal structure.
  • Benefits:
    • Provides a uniform way to traverse collections.
    • Supports multiple traversal algorithms.
  • Liabilities:
    • Can be inefficient for certain data structures.
    • Increases complexity.
  • Related Patterns: Composite, Factory Method, Memento.

Mediator

  • Intent: Define an object that encapsulates how a set of objects interact. Promotes loose coupling by keeping objects from referring to each other explicitly.
  • Use Case: In a chat application, a mediator pattern can facilitate communication between multiple users by centralizing message passing and routing logic, allowing users to send and receive messages without needing direct connections.
  • Benefits:
    • Centralizes communication between objects.
    • Reduces coupling.
  • Liabilities:
    • Can become complex with many mediated classes.
    • Can introduce a single point of failure.
  • Related Patterns: Facade, Observer.

Memento

  • Intent: Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.
  • Use Case: In a text editor application, a memento pattern can capture and store the state of the editor (e.g., text content, cursor position) so that users can undo/redo changes or restore previous editing sessions.
  • Benefits:
    • Captures and restores an object's state.
    • Supports undo mechanisms.
  • Liabilities:
    • Can introduce overhead.
    • May violate encapsulation.
  • Related Patterns: Command, Iterator.

Observer

  • Intent: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
  • Use Case: In a stock market monitoring system, an observer pattern can notify investors about changes in stock prices, allowing them to react to market fluctuations in real-time.
  • Benefits:
    • Notifies dependent objects of changes.
    • Supports loose coupling.
  • Liabilities:
    • Can lead to update overhead.
    • Can be difficult to debug.
  • Related Patterns: Mediator, Singleton.

State

  • Intent: Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
  • Use Case: In a vending machine controller, a state pattern can represent different states of the machine (e.g., idle, selecting, dispensing) and transition between them based on user interactions and internal conditions.
  • Benefits:
    • Allows an object to change its behavior dynamically.
    • Simplifies code.
  • Liabilities:
    • Can lead to a proliferation of state classes.
    • Can be difficult to understand.
  • Related Patterns: Singleton, Flyweight.

Strategy

  • Intent: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
  • Use Case: In a sorting algorithm library, a strategy pattern can encapsulate different sorting algorithms (e.g., quicksort, mergesort) as strategies, allowing users to choose the appropriate strategy based on the size and nature of the data to be sorted.
  • Benefits:
    • Defines a family of algorithms.
    • Promotes code reuse and flexibility.
  • Liabilities:
    • Can introduce complexity with many strategy classes.
    • Can be difficult to choose the right strategy.
  • Related Patterns: Flyweight.

Template Method

  • Intent: Define the skeleton of an algorithm in the superclass but let subclasses override specific steps of the algorithm without changing its structure.
  • Use Case: In a web framework, a template method pattern can define a skeletal structure for handling HTTP requests, with specific steps implemented by subclasses to handle different types of requests (e.g., GET, POST).
  • Benefits:
    • Defines the skeleton of an algorithm.
    • Allows subclasses to customize certain steps.
  • Liabilities:
    • Can lead to inflexible designs.
    • May violate the Liskov Substitution Principle.
  • Related Patterns: Strategy, Factory Method.

Visitor

  • Intent: Represent an operation to be performed on elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
  • Use Case: In a compiler or interpreter framework, a visitor pattern can traverse and analyze abstract syntax trees (ASTs), allowing for operations such as type checking, optimization, and code generation to be performed on the tree nodes.
  • Benefits:
    • Separates operations from the objects on which they operate.
    • Supports adding new operations.
  • Liabilities:
    • Can lead to a proliferation of visitor classes.
    • May violate encapsulation.
  • Related Patterns: Composite, Interpreter.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages