Simply generates an instance for client without exposing any instantiation logic to the client
Useful When
Creating an object is more than a few assignments and involves some logic, put it in a dedicated factory instead of repeating the same code everywhere
Factory Method
Definition
It provides a way to delegate the instantiation logic to child classes
Useful When
There is some generic processing in a class but the required sub-class is dynamically decided at runtime. Or putting it in other words, when the client doesn't know what exact sub-class it might need.
Abstract Factory
Definition
A factory of factories; a factory that groups the individual but related/dependent factories together without specifying their concrete classes
Useful When
There are interrelated dependencies with not-that-simple creation logic involved
Builder
Definition
Allows you to create different flavors of an object while avoiding constructor pollution
Useful When
There could be several flavors of an object and to avoid constructor telescoping
When there are a lot of steps involved in creation of an object
Prototype
Definition
Create object based on an existing object through cloning
Useful When
An object is required that is similar to existing object or when the creation would be expensive as compared to cloning
Singleton
Definition
Ensures that only one object of a particular class is ever created
Actually considered an anti-pattern and overuse of it should be avoided
Introduces a global state in your application and change to it in one place could affect in the other areas
Makes your code tightly coupled
Mocking the singleton could be difficult
Useful When
Only one object of a particular class is needed
Structural
Definition
Concerned with object composition or in other words how the entities can use each other.
They help in answering "How to build a software component?
Types
Adapter
Definition
Wrap an incompatible object in an adapter to make it compatible with another class
Useful When
Making the interface of an existing class to be used as another interface
Bridge
Definition
Preferring composition over inheritance
Implementation details are pushed from a hierarchy to another object with a separate hierarchy
Useful When
Decoupling an abstraction from its implementation so that the two can vary independently
Composite
Definition
Lets clients treat the individual objects in a uniform manner
Describes a group of objects that is treated the same way as a single instance of the same type of object
Useful When
Representing Part-Whole hierarchy
Example
A manager is a type of Employee
A developer is a type of Employee
A manager can manage a list of developers
Composite pattern allows accessing both classes in the same way
Decorator
Definition
Dynamically change the behavior of an object at run time by wrapping them in an object of a decorator class
Useful When
Add behaviors to an individual object without affecting the behavior of other objects from the same class
Facade
Definition
Provides a simplified interface to a complex subsystem
Useful When
Wrap a complex class to provide a convenient interface
Flyweight
Definition
Minimize memory usage or computational expenses by sharing as much as possible with similar objects
Use a dictionary to store the unchanged/immutable object and reuse
Useful When
Need to create a large number of similar objects (10^5)
Proxy
Definition
A class functioning as an interface to something else. A proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes
Use of the proxy can simply be forwarding to the real object, or can provide additional logic
AKA Surrogates, handles or wrappers
Close to Adapters and Decorators
Behavioral
Definition
Concerned with assignment of responsibilities between the objects
Different from structural patterns
Don't just specify the structure but also outline the patterns for message passing/communication between them
They assist in answering "How to run a behavior in software component?"
Types
Chain of Responsibility
Definition
Building a chain of objects
Request enters from one end and keeps going from object to object till it finds the suitable handler
A source of command objects
A series of processing objects
Chained together
Each processing objects execute the commands it can handle, and pass the rest to next
Command
Definition
Encapsulate actions in objects
Provide the means to decouple client from receiver
Client asks Invoker to execute Command
Invoker forward the request to Receiver
Command object
Encapsulates
Parameter Values
Object for the Method
Method Name
Knows how to
execute()
undo()
redo()
Useful When
Implementing a transaction based system
Maintaining a history of commands
Iterator
Definition
A way to access the elements of an aggregate object without exposing its underlying representation
No need to worry about different ways to iterate over a primitive array or ArrayList
Commonly Used
Iterator Interface
for-each loop
Mediator
Definition
Adds a third party object (called mediator) to control the interaction between two objects (called colleagues)
Helps reduce the coupling between the classes communicating with each other
Because now they don't need to have the knowledge of each other's implementation
Memento
Definition
Capturing and storing the current state of an object in a manner that it can be restored later on in a smooth manner
Provides the ability to restore an object to its previous state (undo via rollback)
Components
Originator
The object for which the state is to be saved
Memento
The object that is going to maintain the state of originator
Caretaker
The object that keeps track of multiple memento
Useful When
Need to provide some sort of undo functionality
Observer
Definition
Defines a dependency between objects so that whenever an object changes its state, all its dependents are notified
Subject maintains a list of its dependents (observers)
Subject notifies observers automatically of any state changes, by calling one of their methods
Visitor
Definition
Visitee
accept() a visitor
uses a class-specific method from visitor
Visitor
visit() a visitee
provides class-specific logic
Separate operational logic from Visitee to Visitor
Can do the same by having an inheritance hierarchy
But then would have to modify the class to add new actions
This pattern cam add new operations to Visitee objects without having to modify them
Just create a new Visitor
Useful When
Perform an operation on a group of similar kind of objects
Strategy
Definition
Allows you to switch the algorithm or strategy based on the situation
Enables an algorithm's behavior to be selected at runtime
AKA Policy Pattern
State
Definition
Allows you change the behavior of a class when the state changes
Implements a state machine in an object-oriented way
A state machine is implemented by implementing each individual state as a derived class of the state pattern interface
Implementing state transitions by invoking methods defined by the pattern's superclass
Can be interpreted as a Strategy Pattern which is able to switch the current strategy through invocations of methods defined in the pattern's interface
Template Method
Definition
Defines the skeleton of how a certain algorithm could be performed
Defers the implementation of those steps to the children classes