Patterns
Creational Patterns:
Diffrent ways of handling object creation:
new: whenever new is used, class has responsibility of the creation of an object instance
Abstracts the instantiation process
Competitive: choosing between prototype or abstract factory
Complimentary: abstract factory, builder and prototype can use singleton
Abstract factory:
gives an interface for creating families of related/dependent objects without specifying their concrete classes
Uses:
Systems that need independence from how products are created, composed, or represented.
Scenarios where families of related objects are designed to work together consistently.
Structure:
Abstract Factory: Defines the interface for creating abstract product objects.
Concrete Factory: Implements creation methods for specific product objects.
Abstract Product: Declares an interface for a type of product.
Concrete Product: Implements the product object to be created.
Issues:
Isolation: Clients depend only on abstract interfaces.
Consistency: Ensures products belong to the same family.
Extensibility Challenges: Adding new products may require changing the factory interface.
Builder:
separate the construction of a complex object from its representation, can create different representations
Uses:
Constructing complex objects where creation is independent of the parts and their assembly.
Scenarios requiring different representations of the same object.
Structure:
Director: constructs objects using builder interface
Builder: abstract interface for create parts of complex object
Concrete Builder: construct and assemble parts of object using builder
Product: complex object being built.
Issues:
Encapsulation: Isolates object construction from its representation.
Consistency: classes have varying representation of complex objects
Factory Method
have interface for object creation but have subclasses decide which class to instantiate
Uses:
Object creation needs to be separate from client code
Object creation is standardized but subclasses can define their own domain objects
Structure:
Product: interface of the objects the factory method creates.
Concrete Product: implements the product interface.
Creator: declares the factory method that returns an object of type Product.
Concrete Creator: overrides the factory method to return an instance of a Concrete Product.
Issues:
Customization: Subclasses define the specific types of objects created.
Decoupling: Object creation logic is separated from client code..
Prototype
use one instance of a class to create all future instances
prototype instance defines the type of objects to create and new objects are created using the prototype
Uses:
Classes to instantiate are specified at runtime
Instances of a class can have multiple combinations of state
Structure:
Prototype: declares an interface for cloning
ConcretePrototype: implements the operation for cloning itself
Singleton
ensures a class has only one instance and a global way to access it
Uses:
real world resources where there is one instance per resource
Structure
Singleton Class: Maintains a static reference to the sole instance.
Provides a method to access this instance (e.g.,
getInstance).
Behavioral Patterns: assignment of responsibilities between objects and the patterns of communications between them
Chain of Responsibility
Passes a request along a chain of handlers, giving multiple objects a chance to process it without coupling the sender to the receiver.
Uses:
Decouples the sender of the request from its receiver.
Allows multiple objects to process a request or pass it along the chain.
Structure:
Handler: Defines the interface for handling requests and setting the "next" handler.
ConcreteHandler: Processes the request or passes it to the next handler in the chain.
Client: Sends the request to the first handler in the chain.
Command Pattern
Turns method calls into objects so they can be queued, logged, or undone.
Uses:
Decouples the request sender (Invoker) from the receiver (the object performing the action).
Supports features like undo, logging, or scheduling commands.
Makes it easy to add new commands without changing existing code.
Structure:
Command: An interface for executing operations.
ConcreteCommand: Binds a receiver object to an action.
Receiver: Performs the requested operation.
Invoker: Triggers the command to execute.
Client: Creates the ConcreteCommand and assigns a Receiver to it.
Interpreter Pattern
Breaks down language rules into objects so they can be processed or evaluated (e.g., parsing math formulas or regular expressions).
Uses:
When a problem can be expressed as a grammar with rules and symbols.
Useful for interpreting math expressions, regular expressions, or configuration files.
Structure:
AbstractExpression: Defines a common
interpretmethod for all grammar elements.TerminalExpression: Handles basic symbols in the grammar (e.g., literals).
NonterminalExpression: Handles combinations of symbols based on grammar rules.
Context: Stores global information needed for interpretation.
Client: Builds the grammar (e.g., syntax tree) and starts the interpretation.
Iterator Pattern
Provides a way to loop through elements of a collection (like a list or array) without exposing its internal structure.
Uses:
Allows consistent traversal for different kinds of collections (e.g., lists, trees).
Separates storing data (collection’s job) from looping through data (iterator’s job).
Structure:
Iterator: Interface for traversing elements (e.g.,
hasNext(),next()).ConcreteIterator: Implements the traversal logic for a specific collection.
Aggregate: Interface for creating an iterator.
ConcreteAggregate: Returns an instance of the appropriate iterator.
Mediator Pattern
Defines a central object (Mediator) to manage how a group of objects interact with each other, promoting loose coupling.
Intent:
Objects don’t talk directly to each other but go through the Mediator, reducing dependencies.
Makes it easier to change interactions without affecting individual objects.
Uses:
When interactions between objects are complex and hard to manage.
To reuse objects without them being tightly connected to others.
Structure:
Mediator: Interface that defines communication between objects.
ConcreteMediator: Coordinates the actions and communication between objects.
Colleague: Refers to the Mediator instead of talking directly to other objects.
Asks the Mediator to handle interactions.
Key Benefits:
Simplifies communication between objects.
Reduces dependencies by replacing many-to-many relationships with one-to-many.
Potential Issue:
The Mediator can become too complex if it takes on too many responsibilities
Memento
Capture and restore an object’s internal state so that it can be used later
Uses:
Implement checkpoints or undo mechanisms
Protects the encapsulation of an object by avoiding direct access to its internal state.
Structure:
Memento: Stores a snapshot of the object's state.
Originator: Creates a memento to capture its state and uses it to restore itself when needed.
Caretaker: Keeps track of the memento(s) and ensures their safekeeping.
Observer
one-to-many relationship so when one object (Subject) changes state, all dependent objects (Observers) are notified automatically.
Uses:
Keeps objects informed about changes in other objects.
Structure:
Subject: Tracks and notifies observers; allows attaching/detaching observers.
Observer: Defines an update method for state changes.
ConcreteSubject: Stores state and notifies observers of changes.
ConcreteObserver: Updates its state to stay consistent with the Subject.
State
Allows a object to alter behavior when its state changes, will appear to change class
Structure:
Context: Interface for clients and holds a reference to the current state object.
State: Interface for defining behavior for different states.
ConcreteState: Implements behavior specific to a particular state.
Strategy
uses a family of algorithms encapsulated in classes allowing them to be swapped without changing the code
Uses:
To provide multiple ways to accomplish a task (e.g., sorting, traveling).
To make algorithms interchangeable and independent from the client.
Structure:
Strategy: Interface for all algorithms.
ConcreteStrategy: Implements a specific algorithm.
Context: Holds a reference to a Strategy and delegates algorithm execution to it.
Template method
Defines the skeleton of an algorithm in a base class, allowing subclasses to handle stepssteps
Uses:
Encapsulate the common behavior of an algorithm while allowing subclasses to customize specific parts.
Avoid duplicate code by sharing the algorithm structure in the base class.
Structure:
AbstractClass: Defines the template method, which outlines the algorithm's steps.
ConcreteClass: Implements specific steps of the algorithm
Visitor Pattern
Allows defining new operations on objects without changing their classes, separating operation logic from the objects.
Uses:
For complex object structures needing multiple unrelated operations.
Adding new operations without modifying existing classes.
Structure:
Element: Defines
accept(Visitor v)and passes itself to the visitor.ConcreteElement: Implements
accept(Visitor v)and calls the visitor's method.Visitor: Interface with methods for each ConcreteElement type.
ConcreteVisitor: Implements specific operations for each element.
Structural Patterns
design patters that define relationships between enteties
Adapter
Converts interface of a class to work with another, wraps existing class with a new interface
Uses:
interface of class does not match the one you need
reusable class that works with unknown classes
Structure:
Wrapper: allows for new application to use legacy class
Bridge
separate abstraction and implementation into their own hierarchies
Uses:
Avoid permanent binding between abstraction and implementation.
Enable independent extension of both abstractions and implementations.
Combine different abstractions with various implementations seamlessly.
Structure:
Implementor: provides simple operations
Abstraction: defines higher-level operations based on implementor:
Composite
Groups objects into a tree structure to organize and work with individual items and groups of items in the same way.
Uses:
Work with both single objects and groups of objects without changing the code.
Combine objects into flexible hierarchies for organization or processing.
Structure:
Component: common interface for all objects in the group.
Leaf: basic individual objects with no children.
Composite: objects that contain and manage groups of other objects.
Decorator
Adds new responsibilities to an object without altering its structure.
alternative to subclassing.
Uses:
Add new functionality to an object at runtime without changing code.
Dynamically combine features without creating a large hierarchy of subclasses.
Structure:
Component: Interface for objects that can be decorated.
Concrete Component: The base object to which responsibilities can be added.
Decorator: Wraps a component and provides additional functionality.
Concrete Decorator: Implements the additional behaviors while maintaining the component interface.
Facade
provide a single interface for multiple interfaces a complex subsystem,
Uses:
Simplify access to a complex system by providing a single entry point.
Laying subsystems
Structure:
Facade: Provides a higher-level interface that wraps the subsystem's components.
Subsystem Classes: The components hidden behind the facade. These are still accessible if needed, but the facade reduces direct interaction.
Flyweight
Each object is divided into two pieces: the
state-dependent (extrinsic): stored in client and passed to flyweight
state-independent(intrinsic) : stored (shared) in the Flyweight object
Uses:
Save memory when working with large numbers of similar objects.
Reduce duplication of shared data across instances.
Structure:
Flyweight: Interface for shared objects.
ConcreteFlyweight: Stores shared (intrinsic) data.
UnsharedConcreteFlyweight: subclasses that are not shared
FlyweightFactory: Creates and manages shared objects.
Proxy
placeholder for another object, controlling access and adding an additional layer of functionality.
Uses:
When a more sophisticated reference to an object is needed instead of a direct pointer.
Control access, add security, or manage resources such as memory or computation.
Structure:
Proxy:
Maintains a reference to the real object (subject).
Implements the same interface as the real object to act as its substitute
Real Subject: The actual object being represented and accessed through the proxy.
Types:
Virtual Proxy: Acts as a placeholder for expensive-to-create objects, loading them only when needed.
Remote Proxy: Represents objects in a different address space (e.g., on a server).
Protective Proxy: Manages access to sensitive objects, ensuring only authorized clients can interact.
Smart Proxy: Adds actions like loading persistent objects or managing concurrency before accessing the real object.
Structural Patterns
design patters that define relationships between enteties
Adapter
Converts interface of a class to work with another, wraps existing class with a new interface
Uses:
interface of class does not match the one you need
reusable class that works with unknown classes
Structure:
Wrapper: allows for new application to use legacy class
Bridge
separate abstraction and implementation into their own hierarchies
Uses:
Avoid permanent binding between abstraction and implementation.
Enable independent extension of both abstractions and implementations.
Combine different abstractions with various implementations seamlessly.
Structure:
Implementor: provides simple operations
Abstraction: defines higher-level operations based on implementor:
Composite
Groups objects into a tree structure to organize and work with individual items and groups of items in the same way.
Uses:
Work with both single objects and groups of objects without changing the code.
Combine objects into flexible hierarchies for organization or processing.
Structure:
Component: common interface for all objects in the group.
Leaf: basic individual objects with no children.
Composite: objects that contain and manage groups of other objects.
Decorator
Adds new responsibilities to an object without altering its structure.
alternative to subclassing.
Uses:
Add new functionality to an object at runtime without changing code.
Dynamically combine features without creating a large hierarchy of subclasses.
Structure:
Component: Interface for objects that can be decorated.
Concrete Component: The base object to which responsibilities can be added.
Decorator: Wraps a component and provides additional functionality.
Concrete Decorator: Implements the additional behaviors while maintaining the component interface.
Facade
provide a single interface for multiple interfaces a complex subsystem,
Uses:
Simplify access to a complex system by providing a single entry point.
Laying subsystems
Structure:
Facade: Provides a higher-level interface that wraps the subsystem's components.
Subsystem Classes: The components hidden behind the facade. These are still accessible if needed, but the facade reduces direct interaction.
Flyweight
Each object is divided into two pieces: the
state-dependent (extrinsic): stored in client and passed to flyweight
state-independent(intrinsic) : stored (shared) in the Flyweight object
Uses:
Save memory when working with large numbers of similar objects.
Reduce duplication of shared data across instances.
Structure:
Flyweight: Interface for shared objects.
ConcreteFlyweight: Stores shared (intrinsic) data.
UnsharedConcreteFlyweight: subclasses that are not shared
FlyweightFactory: Creates and manages shared objects.
Proxy
placeholder for another object, controlling access and adding an additional layer of functionality.
Uses:
When a more sophisticated reference to an object is needed instead of a direct pointer.
Control access, add security, or manage resources such as memory or computation.
Structure:
Proxy:
Maintains a reference to the real object (subject).
Implements the same interface as the real object to act as its substitute
Real Subject: The actual object being represented and accessed through the proxy.
Types:
Virtual Proxy: Acts as a placeholder for expensive-to-create objects, loading them only when needed.
Remote Proxy: Represents objects in a different address space (e.g., on a server).
Protective Proxy: Manages access to sensitive objects, ensuring only authorized clients can interact.
Smart Proxy: Adds actions like loading persistent objects or managing concurrency before accessing the real object.