Tuesday, April 14, 2015

Design Pattern Cheat Sheet



Creational Patterns
Creational design patterns abstract the instantiation process. They help make a system independent of how its objects are created, composed, and represented. A class creational pattern uses inheritance to vary the class that’s instantiated, whereas an object creational pattern will delegate instantiation to another object.
Creational patterns become important as systems evolve to depend more on object composition than class inheritance. As that happens, emphasis shifts away from hard-coding a fixed set of behaviors toward defining a smaller set of fundamental behaviors that can be composed into any number of more complex ones. Thus creating objects with particular behaviors requires more than simply instantiating a class.

OC:Abstract Factory - Provide an interface for creating families of related or dependent objects without specifying their concrete classes.




AbstractFactory (WidgetFactory) – declares an interface for operations that create abstract product objects.
ConcreteFactory (MotifWidgetFactory, PMWidgetFactory) – implements the operations to create concrete product objects.
BstractProduct (Window, ScrollBar) – declares an interface for a type of pproduct object.
ConcreteProduct (MotifWindow, MotifScrollBar) – defines a product object to be created by the corresponding concrete factory. – implements the AbstractProduct interface.
Client – uses only interfaces declared by AbstractFactory and AbstractProduct classes.

OC:Builder - Separate the construction of a complex object from its representation so that the same construction process can create different representations.


Builder (TextConverter) – specifies an abstract interface for creating parts of a Product object.

ConcreteBuilder (ASCIIConverter, TeXConverter, TextWidgetConverter)– constructs and assembles parts of the product by implementing the Builder

interface. – defines and keeps track of the representation it creates. – provides an interface for retrieving the product (e.g., GetASCIIText, Get-Text Widget).

Director (RTFReader) – constructs an object using the Builder interface.

Product (ASCIIText, TeXText, TextWidget) – represents the complex object under construction. ConcreteBuilder builds the product’s internal representation and defines the process by which it’s assembled. – includes classes that define the constituent parts, including interfaces for assembling the parts into the final result.

CC:Factory Method
- Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. (Virtual Constructor)












Product (Document) – defines the interface of objects the factory method creates.
ConcreteProduct (MyDocument) – implements the Product interface.
Creator (Application) – declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object. – may call the factory method to create a Product object.
ConcreteCreator (MyApplication) – overrides the factory method to return an instance of a ConcreteProduct.

OC:Prototype - Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

Prototype (Graphic) – declares an interface for cloning itself.
ConcretePrototype (Staff, WholeNote, HalfNote) – implements an operation for cloning itself.
Client (GraphicTool) – creates a new object by asking a prototype to clone itself.


OC:Singleton - Ensure a class only has one instance, and provide a global point of access to it.






 

Singleton – defines an Instance operation that lets clients access its unique instance. Instance is a class operation (that is, a class method in Smalltalk and a static member function in C++). – may be responsible for creating its own unique instance.
























Structural Patterns
Structural patterns are concerned with how classes and objects are composed to form larger structures. Structural class patterns use inheritance to compose interfaces or implementations. As a simple example, consider how multiple inheritance mixes two or more classes into one. The result is a class that combines the properties of its parent classes. This pattern is particularly useful for making independently developed class libraries work together. Another example is the class form of the Adapter pattern. In general, an adapter makes one interface (the adaptee’s) conform to another, thereby providing a uniform abstraction of different interfaces. A class adapter accomplishes this by inheriting privately from an adaptee class. The adapter then expresses its interface in terms of the adaptee’s.
Rather than composing interfaces or implementations, structural object patterns describe ways to compose objects to realize new functionality. The added flexibility of object composition comes from the ability to change the composition at run-time, which is impossible with static class composition.


C,OS: Adapter - Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

Target (Shape) – defines the domain-specific interface that Client uses.
Client (DrawingEditor) – collaborates with objects conforming to the Target interface.
Adaptee (TextView)– defines an existing interface that needs adapting.
Adapter (TextShape) – adapts the interface of Adaptee to the Target interface.



OS:Bridge - Decouple an abstraction from its implementation so that the two can vary independently.


Abstraction (Window) – defines the abstraction’s interface. – maintains a reference to an object of type Implementor.
RefmedAbstraction (IconWindow) – Extends the interface defined by Abstraction.
Implementor (WindowImp) – defines the interface for implementation classes. This interface doesn’t have to correspond exactly to Abstraction’s interface; in fact the two interfaces can be quite different. Typically the Implementor interface provides only primitive operations, and Abstraction defines higher-level operations based on these primitives.
ConcreteImplementor (XWindowImp, PMWindowImp) – implements the Implementor interface and defines its concrete implementation.


OS:Composite - Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

Component (Graphic) – declares the interface for objects in the composition. – implements default behavior for the interface common to all classes, as appropriate. – declares an interface for accessing and managing its child component. – (optional) defines an interface for accessing a component’s parent in the recursive structure, and implements it if that’s appropriate.
Leaf (Rectangle, Line, Text, etc.) – represents leaf objects in the composition. A leaf has no children. – defines behavior for primitive objects in the composition.
Composite (Picture) – defines behavior for components having children. – stores child components. – implements child-related operations in the Component interface.
Client – manipulates objects in the composition through the Component interface.




OS:Decorator - Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.


Component (VisualComponent) – defines the interface for objects that can have responsibilities added to them dynamically.
ConcreteComponent (TextView) – 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 (BorderDecorator, ScrollDecorator) – adds responsibilities to the component.


OS:Facade - Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.


Facade (Compiler) – knows which subsystem classes are responsible for a request. – delegates client requests to appropriate subsystem objects.
subsystem classes (Scanner, Parser, ProgramNode, etc.) – implement subsystem functionality. – handle work assigned by the Facade object. – have no knowledge of the facade; that is, they keep no references to it.


OS:Flyweight - Use sharing to support large numbers of fine-grained objects efficiently.


Flyweight (Glyph) – declares an interface through which flyweights can receive and act on extrinsic state.
ConcreteFlyweight (Character) – implements the Flyweight interface and adds storage for intrinsic state, if any. A ConcreteFlyweight object must be sharable. Any state it stores must be intrinsic; that is, it must be independent of the ConcreteFlyweight object’s context.
UnsharedConcreteFlyweight (Row, Column) – not all Flyweight subclasses need to be shared. The Flyweight interface enables sharing; it doesn’t enforce it. It’s common for UnsharedConcreteFlyweight objects to have ConcreteFlyweight objects as children at some level in the flyweight object structure (as the Row and Column classes have).
FlyweightFactory – creates and manages flyweight objects. – ensures that flyweights are shared properly. When a client requests a flyweight, the FlyweightFactory object supplies an existing instance or creates one, if none exists.
Client – maintains a reference to flyweight(s). – computes or stores the extrinsic state of flyweight(s).

OS:Proxy - Provide a surrogate or placeholder for another object to control access to it.


Proxy (ImageProxy) – maintains a reference that lets the proxy access the real subject. Proxy may refer to a Subject if the RealSubject and Subject interfaces are the same. – provides an interface identical to Subject’s so that a proxy can by substituted for the real subject. – controls access to the real subject and may be responsible for creating and deleting it. – other responsibilities depend on the kind of proxy: (i) remote proxies - are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space. (ii) virtual proxies - may cache additional information about the real subject so that they can postpone accessing it. For example, the ImageProxy from the Motivation caches the real image’s extent. (iii) protection proxies - check that the caller has the access permissions required to perform a request.
Subject (Graphic) – defines the common interface for RealSubject and Proxy so that a Proxy can be used anywhere a RealSubject is expected.
RealSubject (Image) – defines the real object that the proxy represents.


Behavioral Patterns
Behavioral patterns are concerned with algorithms and the assignment of responsibilities between objects. Behavioral patterns describe not just patterns of objects or classes but also the patterns of communication between them. These patterns characterize complex control flow that’s difficult to follow at run-time. They shift your focus away from flow of control to let you concentrate just on the way objects are interconnected.
OB:Chain of Responsibility - 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.


Handler (HelpHandler) – defines an interface for handling requests. – (optional) implements the successor link.
ConcreteHandler (PrintButton, PrintDialog) – handles requests it is responsible for. – can access its successor. – if the ConcreteHandler can handle the request, it does so; otherwise it forwards the request to its successor.
Client – initiates the request to a ConcreteHandler object on the chain.

OB:Command - Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.


Command – declares an interface for executing an operation.
ConcreteCommand (PasteCommand, OpenCommand) – defines a binding between a Receiver object and an action. – implements Execute by invoking the corresponding operation(s) on Receiver.
Client (Application)– creates a ConcreteCommand object and sets its receiver.
Invoker (Menultem) – asks the command to carry out the request.
Receiver (Document, Application)– knows how to perform the operations associated with carrying out a request. Any class may serve as a Receiver.


CB:Interpreter - Given a language, define a represention for its grammar along with an interpreter that uses the representation to interpret sentences in the language.


AbstractExpression (RegularExpression) – declares an abstract Interpret operation that is common to all nodes in the abstract syntax tree.
TerminalExpression (LiteralExpression) – implements an Interpret operation associated with terminal symbols in the grammar. – an instance is required for every terminal symbol in a sentence.
NonterminalExpression (AlternationExpression, RepetitionExpression, SequenceExpressions) – one such class is required for every rule R ::= R1R2...Rn in the grammar. – maintains instance variables of type AbstractExpression for each of the symbols R1 through Rn.– implements an Interpret operation for nonterminal symbols in the grammar. Interpret typically calls itself recursively on the variables representing R1 through Rn.
Context – contains information that’s global to the interpreter.
Client – builds (or is given) an abstract syntax tree representing a particular sentence in the language that the grammar defines. The abstract syntax tree is assembled from instances of the NonterminalExpression and TerminalExpression classes. – invokes the Interpret operation.










OB:Iterator - Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.


Iterator – defines an interface for accessing and traversing elements.
ConcreteIterator – implements the Iterator interface. – keeps track of the current position in the traversal of the aggregate.
Aggregate – defines an interface for creating an Iterator object.
ConcreteAggregate – implements the Iterator creation interface to return an instance of the proper ConcreteIterator.






OB:Mediator - Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.


Mediator (DialogDirector) – defines an interface for communicating with Colleague objects.
ConcreteMediator (FontDialogDirector) – implements cooperative behavior by coordinating Colleague objects. – knows and maintains its colleagues.
Colleague classes (ListBox, EntryField) – each Colleague class knows its Mediator object. – each colleague communicates with its mediator whenever it would have otherwise communicated with another colleague.


OB:Memento - Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later.

Memento (SolverState) – stores internal state of the Originator object. The memento may store as much or as little of the originator’s internal state as necessary at its originator’s discretion. – protects against access by objects other than the originator. Mementos have effectively two interfaces. Caretaker sees a narrow interface to the Memento—it can only pass the memento to other objects. Originator, in contrast, sees a wide interface, one that lets it access all the data necessary to restore itself to its previous state. Ideally, only the originator that produced the memento would be permitted to access the memento’s internal state.
Originator (ConstraintSolver) – creates a memento containing a snapshot of its current internal state. – uses the memento to restore its internal state.
Caretaker (undo mechanism)– is responsible for the memento’s safekeeping. – never operates on or examines the contents of a memento.






OB:Observer - Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.


Subject – knows its observers. Any number of Observer objects may observe a subject. – provides an interface for attaching and detaching Observer objects.
Observer – defines an updating interface for objects that should be notified of changes in a subject.
ConcreteSubject – stores state of interest to ConcreteObserver objects. – sends a notification to its observers when its state changes.
ConcreteObserver – maintains a reference to a ConcreteSubject object.
stores state that should stay consistent with the subject’s. – implements the Observer updating interface to keep its state consistent with the subject’s.


OB:State - Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

Context (TCPConnection) – defines the interface of interest to clients. – maintains an instance of a ConcreteState subclass that defines the current state.
State (TCPState) – defines an interface for encapsulating the behavior associated with a particular state of the Context.
ConcreteState subclasses (TCPEstablished, TCPListen, TCPClosed) – each subclass implements a behavior associated with a state of the Context.




OB:Strategy - Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.


Strategy (Compositor) – declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy.
ConcreteStrategy (SimpleCompositor, TeXCompositor, ArrayCompositor) – implements the algorithm using the Strategy interface.
Context (Composition) – is configured with a ConcreteStrategy object. – maintains a reference to a Strategy object. – may define an interface that lets Strategy access its data.


CB:Template Method - Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.


AbstractClass (Application) – defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm. – implements a template method defining the skeleton of an algorithm. The template method calls primitive operations as well as operations defined in AbstractClass or those of other objects.
ConcreteClass (MyApplication) – implements the primitive operations to carry out subclass-specific steps of the algorithm.


OB:Visitor - Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.


Visitor (NodeVisitor) – declares a Visit operation for each class of ConcreteElement in the object structure. The operation’s name and signature identifies the class that sends the Visit request to the visitor. That lets the visitor determine the concrete class of the element being visited. Then the visitor can access the element directly through its particular interface.
Concrete Visitor (TypeCheckingVisitor) – implements each operation declared by Visitor. Each operation implements a fragment of the algorithm defined for the corresponding class of object in the structure. ConcreteVisitor provides the context for the algorithm and stores its local state. This state often accumulates results during the traversal of the structure.
Element (Node) – defines an Accept operation that takes a visitor as an argument.
ConcreteElement (AssignmentNode, VariableRefNode) – implements an Accept operation that takes a visitor as an argument.
ObjectStructure (Program) – can enumerate its elements. – may provide a high-level interface to allow the visitor to visit its elements. – may either be a composite or a collection such as a list or a set.

1 comment:

  1. Great Sachin.
    thanks for your hard work. this helped me alot

    ReplyDelete