Design patterns
Creational Design Patterns
Creational design patterns focus on object creation mechanisms.
They provide flexibility and encapsulation in object creation
processes.
Creational patterns address various requirements, such as:
• Controlling object instantiation
• Enhancing flexibility in creating objects
• Promoting reuse and configurability
Example: Singleton, Factory Method, Abstract Factory, Builder,
Prototype
Singleton Pattern
• Ensures a class has only one instance and provides a global point of
access to that instance.
• Commonly used for logging, database connections, and configuration
settings.
• Example: In a logging system, the Singleton pattern ensures there's
only one instance of the logger object shared across the application.
Factory Method Pattern
• Defines an interface for creating objects, but subclasses decide which
class to instantiate.
• Encapsulates object creation logic in subclasses.
• Example: In a vehicle manufacturing system, the Factory Method
pattern allows each vehicle type (car, bike, truck) to have its factory
method for creating instances.
Abstract Factory Pattern
• Provides an interface for creating families of related or dependent
objects without specifying their concrete classes.
• Encourages loose coupling between client code and concrete classes.
• Example: In a GUI framework, an abstract factory can create different
types of buttons, text boxes, and dropdowns for various operating
systems (Windows, macOS, Linux).
Builder Pattern
• Separates the construction of a complex object from its representation,
allowing the same construction process to create different
representations.
• Supports the creation of objects with varied configurations.
• Example: In a meal ordering system, the Builder pattern can be used to
construct different types of meals (e.g., vegetarian, non-vegetarian)
with customizable options (e.g., size, toppings).
•
Prototype Pattern
• Creates new objects by copying an existing instance, known as the
prototype.
• Avoids the need for subclassing to create new objects.
• Example: In a graphic design tool, the Prototype pattern allows users
to clone existing shapes and modify them to create new shapes without
having to define a new class for each variation.
Structural Design Patterns
• Structural design patterns focus on class and object composition.
• They enhance code organization, flexibility, and reusability.
• Structural patterns describe how objects and classes can be combined
to form larger structures.
• Example: Adapter, Bridge, Composite, Decorator, Facade, Flyweight,
Proxy.
Adapter Pattern
• Allows incompatible interfaces to work together by providing a bridge
between them.
• Translates one interface into another without changing the existing
code.
• Example: Adapting a third-party payment gateway interface to work
with an existing e-commerce system by implementing an adapter that
converts the gateway's interface into a standard interface expected by
the system.
Bridge Pattern
• Decouples an abstraction from its implementation, allowing them to
vary independently.
• Provides flexibility in designing large systems by separating
abstractions from their implementations.
• Example: In a drawing application, the Bridge pattern separates the
shape abstraction (e.g., circle, square) from its rendering
implementation (e.g., OpenGL, DirectX).
Composite Pattern
• Composes objects into tree structures to represent part-whole
hierarchies.
• Allows clients to treat individual objects and compositions of objects
uniformly.
• Example: In a file system, files and directories can be represented as
leaf and composite components, respectively, allowing recursive
operations to be performed on the entire structure.
Decorator Pattern
• Attaches additional responsibilities to objects dynamically.
• Provides a flexible alternative to subclassing for extending
functionality.
• Example: In a text processing application, the Decorator pattern allows
text formatting decorators (e.g., bold, italic) to be applied to a base text
object, enabling the creation of rich-text documents.
Facade Pattern
• Provides a unified interface to a set of interfaces in a subsystem.
• Simplifies the complexity of the subsystem and hides its
implementation details.
• Example: In a multimedia player application, a Facade can provide a
single interface for managing playback (play, pause, stop) and
handling different media formats (audio, video).
Flyweight Pattern
• Minimizes memory usage or computational expenses by sharing as
much as possible with related objects.
• Stores common and intrinsic states externally and shares them among
multiple objects.
• Example: In a text editing application, the Flyweight pattern can be
used to store shared font styles (e.g., Arial, Times New Roman) and
reuse them across multiple text objects.
Proxy Pattern
• Provides a placeholder for another object to control access, reduce
cost, or add functionality.
• Acts as a surrogate or placeholder for the real object.
• Example: In a remote service invocation system, a Proxy can represent
a remote object and handle communication details such as network
communication and authentication.
•
Behavioral Design Patterns
• Behavioral design patterns focus on communication between objects
and their responsibilities.
• They address how objects interact and fulfill individual
responsibilities.
• Behavioral patterns promote flexibility, modularity, and extensibility
in software design.
• Example: Observer, Strategy, Chain of Responsibility, Command,
State, Interpreter, Mediator, Memento, Visitor.
Observer Pattern
• Defines a one-to-many dependency between objects, ensuring that
when one object changes state, all its dependents are notified and
updated automatically.
• Enables loose coupling between subjects and observers.
• Example: In a weather monitoring system, the Observer pattern allows
multiple weather displays to be updated whenever the weather
conditions change, ensuring real-time data synchronization.
Strategy Pattern
• Defines a family of algorithms, encapsulates each one, and makes
them interchangeable.
• Allows algorithms to vary independently from clients that use them.
• Example: In a payment processing system, the Strategy pattern enables
different payment methods (e.g., credit card, PayPal) to be
encapsulated as strategies, which can be selected dynamically based
on user preferences.
Chain of Responsibility Pattern
• Allows multiple objects to handle a request without the sender needing
to know which object will handle it.
• Forms a chain of handler objects, each processing the request or
passing it to the next handler in the chain.
• Example: In an approval workflow system, the Chain of
Responsibility pattern can be used to create a sequence of approvers
(e.g., manager, director, CEO) where each approver decides whether to
approve or forward the request to the next level.
•
Command Pattern
• Encapsulates a request as an object, thereby allowing for
parameterization of clients with queues, requests, and operations.
• Enables the invocation of commands without knowing the requested
operation or the receiver's identity.
• Example: In a remote control application, the Command pattern
encapsulates various device actions (e.g., turn on, turn off, change
channel) as command objects, allowing users to queue and execute
commands sequentially.
Interpreter Pattern
• Defines a grammar for interpreting a language and provides a way to
evaluate sentences in that language.
• Used to represent and evaluate simple grammatical expressions.
• Example: Parsing and evaluating mathematical expressions provided
as strings.
Iterator Pattern
• Provides a way to access elements of an aggregate object sequentially
without exposing its underlying representation.
• Enables traversal of collections without knowing their internal
structure.
• Example: Iterating over the elements of a list, array, or tree data
structure without exposing the details of their implementation.
Mediator Pattern
• Defines an object that encapsulates how a set of objects interact.
• Promotes loose coupling between communicating objects by
centralizing interaction logic.
• Example: Implementing a chat room where users communicate with
each other through a central mediator object rather than directly.
Memento Pattern
• Captures and externalizes an object's internal state so that the object
can be restored to this state later.
• Allows for undo/redo functionality and restoring an object to a
previous state.
• Example: Implementing undo functionality in a text editor to revert
changes made to a document.
State Pattern
• Allows an object to alter its behavior when its internal state changes.
• Encapsulates state-specific behavior into separate state objects.
• Example: Implementing a vending machine where its behavior
changes based on its current state (e.g., idle, dispensing, out of stock).
Template Method Pattern
• The Template Method pattern defines the skeleton of an algorithm in a
method, deferring some steps to subclasses.
• Allows subclasses to redefine certain steps of an algorithm without
changing its structure.
• Encourages code reuse and ensures consistency in algorithm behavior
across subclasses.
• Example: In a document processing application, the Template Method
pattern can be used to define a common process for opening, editing,
and saving documents, with specific steps (e.g., file format
conversion) implemented by subclasses for different document types.
Visitor
• The Visitor pattern is a behavioral design pattern that allows adding
new operations to existing classes without modifying their structure.
• It separates the algorithm from the object structure on which it
operates.
• Enables performing operations on a group of related objects with
different concrete implementations.
• Useful when the structure of objects is stable but the operations on
them vary and need to be added or changed over time.
References
• https://refactoring.guru/design-patterns

software engineering Design Patterns.pdf

  • 1.
  • 2.
    Creational Design Patterns Creationaldesign patterns focus on object creation mechanisms. They provide flexibility and encapsulation in object creation processes. Creational patterns address various requirements, such as: • Controlling object instantiation • Enhancing flexibility in creating objects • Promoting reuse and configurability Example: Singleton, Factory Method, Abstract Factory, Builder, Prototype
  • 3.
    Singleton Pattern • Ensuresa class has only one instance and provides a global point of access to that instance. • Commonly used for logging, database connections, and configuration settings. • Example: In a logging system, the Singleton pattern ensures there's only one instance of the logger object shared across the application.
  • 4.
    Factory Method Pattern •Defines an interface for creating objects, but subclasses decide which class to instantiate. • Encapsulates object creation logic in subclasses. • Example: In a vehicle manufacturing system, the Factory Method pattern allows each vehicle type (car, bike, truck) to have its factory method for creating instances.
  • 5.
    Abstract Factory Pattern •Provides an interface for creating families of related or dependent objects without specifying their concrete classes. • Encourages loose coupling between client code and concrete classes. • Example: In a GUI framework, an abstract factory can create different types of buttons, text boxes, and dropdowns for various operating systems (Windows, macOS, Linux).
  • 6.
    Builder Pattern • Separatesthe construction of a complex object from its representation, allowing the same construction process to create different representations. • Supports the creation of objects with varied configurations. • Example: In a meal ordering system, the Builder pattern can be used to construct different types of meals (e.g., vegetarian, non-vegetarian) with customizable options (e.g., size, toppings). •
  • 7.
    Prototype Pattern • Createsnew objects by copying an existing instance, known as the prototype. • Avoids the need for subclassing to create new objects. • Example: In a graphic design tool, the Prototype pattern allows users to clone existing shapes and modify them to create new shapes without having to define a new class for each variation.
  • 8.
    Structural Design Patterns •Structural design patterns focus on class and object composition. • They enhance code organization, flexibility, and reusability. • Structural patterns describe how objects and classes can be combined to form larger structures. • Example: Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy.
  • 9.
    Adapter Pattern • Allowsincompatible interfaces to work together by providing a bridge between them. • Translates one interface into another without changing the existing code. • Example: Adapting a third-party payment gateway interface to work with an existing e-commerce system by implementing an adapter that converts the gateway's interface into a standard interface expected by the system.
  • 10.
    Bridge Pattern • Decouplesan abstraction from its implementation, allowing them to vary independently. • Provides flexibility in designing large systems by separating abstractions from their implementations. • Example: In a drawing application, the Bridge pattern separates the shape abstraction (e.g., circle, square) from its rendering implementation (e.g., OpenGL, DirectX).
  • 11.
    Composite Pattern • Composesobjects into tree structures to represent part-whole hierarchies. • Allows clients to treat individual objects and compositions of objects uniformly. • Example: In a file system, files and directories can be represented as leaf and composite components, respectively, allowing recursive operations to be performed on the entire structure.
  • 12.
    Decorator Pattern • Attachesadditional responsibilities to objects dynamically. • Provides a flexible alternative to subclassing for extending functionality. • Example: In a text processing application, the Decorator pattern allows text formatting decorators (e.g., bold, italic) to be applied to a base text object, enabling the creation of rich-text documents.
  • 13.
    Facade Pattern • Providesa unified interface to a set of interfaces in a subsystem. • Simplifies the complexity of the subsystem and hides its implementation details. • Example: In a multimedia player application, a Facade can provide a single interface for managing playback (play, pause, stop) and handling different media formats (audio, video).
  • 14.
    Flyweight Pattern • Minimizesmemory usage or computational expenses by sharing as much as possible with related objects. • Stores common and intrinsic states externally and shares them among multiple objects. • Example: In a text editing application, the Flyweight pattern can be used to store shared font styles (e.g., Arial, Times New Roman) and reuse them across multiple text objects.
  • 15.
    Proxy Pattern • Providesa placeholder for another object to control access, reduce cost, or add functionality. • Acts as a surrogate or placeholder for the real object. • Example: In a remote service invocation system, a Proxy can represent a remote object and handle communication details such as network communication and authentication. •
  • 16.
    Behavioral Design Patterns •Behavioral design patterns focus on communication between objects and their responsibilities. • They address how objects interact and fulfill individual responsibilities. • Behavioral patterns promote flexibility, modularity, and extensibility in software design. • Example: Observer, Strategy, Chain of Responsibility, Command, State, Interpreter, Mediator, Memento, Visitor.
  • 17.
    Observer Pattern • Definesa one-to-many dependency between objects, ensuring that when one object changes state, all its dependents are notified and updated automatically. • Enables loose coupling between subjects and observers. • Example: In a weather monitoring system, the Observer pattern allows multiple weather displays to be updated whenever the weather conditions change, ensuring real-time data synchronization.
  • 18.
    Strategy Pattern • Definesa family of algorithms, encapsulates each one, and makes them interchangeable. • Allows algorithms to vary independently from clients that use them. • Example: In a payment processing system, the Strategy pattern enables different payment methods (e.g., credit card, PayPal) to be encapsulated as strategies, which can be selected dynamically based on user preferences.
  • 19.
    Chain of ResponsibilityPattern • Allows multiple objects to handle a request without the sender needing to know which object will handle it. • Forms a chain of handler objects, each processing the request or passing it to the next handler in the chain. • Example: In an approval workflow system, the Chain of Responsibility pattern can be used to create a sequence of approvers (e.g., manager, director, CEO) where each approver decides whether to approve or forward the request to the next level. •
  • 20.
    Command Pattern • Encapsulatesa request as an object, thereby allowing for parameterization of clients with queues, requests, and operations. • Enables the invocation of commands without knowing the requested operation or the receiver's identity. • Example: In a remote control application, the Command pattern encapsulates various device actions (e.g., turn on, turn off, change channel) as command objects, allowing users to queue and execute commands sequentially.
  • 21.
    Interpreter Pattern • Definesa grammar for interpreting a language and provides a way to evaluate sentences in that language. • Used to represent and evaluate simple grammatical expressions. • Example: Parsing and evaluating mathematical expressions provided as strings.
  • 22.
    Iterator Pattern • Providesa way to access elements of an aggregate object sequentially without exposing its underlying representation. • Enables traversal of collections without knowing their internal structure. • Example: Iterating over the elements of a list, array, or tree data structure without exposing the details of their implementation.
  • 23.
    Mediator Pattern • Definesan object that encapsulates how a set of objects interact. • Promotes loose coupling between communicating objects by centralizing interaction logic. • Example: Implementing a chat room where users communicate with each other through a central mediator object rather than directly.
  • 24.
    Memento Pattern • Capturesand externalizes an object's internal state so that the object can be restored to this state later. • Allows for undo/redo functionality and restoring an object to a previous state. • Example: Implementing undo functionality in a text editor to revert changes made to a document.
  • 25.
    State Pattern • Allowsan object to alter its behavior when its internal state changes. • Encapsulates state-specific behavior into separate state objects. • Example: Implementing a vending machine where its behavior changes based on its current state (e.g., idle, dispensing, out of stock).
  • 26.
    Template Method Pattern •The Template Method pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. • Allows subclasses to redefine certain steps of an algorithm without changing its structure. • Encourages code reuse and ensures consistency in algorithm behavior across subclasses. • Example: In a document processing application, the Template Method pattern can be used to define a common process for opening, editing, and saving documents, with specific steps (e.g., file format conversion) implemented by subclasses for different document types.
  • 27.
    Visitor • The Visitorpattern is a behavioral design pattern that allows adding new operations to existing classes without modifying their structure. • It separates the algorithm from the object structure on which it operates. • Enables performing operations on a group of related objects with different concrete implementations. • Useful when the structure of objects is stable but the operations on them vary and need to be added or changed over time.
  • 28.