These are notes I made while preparing for SCEA 5. I would like to thank my friend Sajitha for helping in scribing these notes.
1. GOF DESIGN PATTERNS
1.1. Abstract Factory
Provide an interface for creating families of related or dependent objects with out specifying their concrete classes
Advantages
- One level of abstraction higher than factory pattern – It is a factory method that returns one of several factories
- It encapsulates a group of individual factories having a common theme
- Isolates concrete classes
- Makes exchanging product families easy
- Promotes consistency among products
Disadvantages
- Supporting new kind of products is difficult
Example EJBHome interface that creates new EJBObjects
javax.servlet.jsp.JSPFactory – Abstract class that defines factory methods available to JSP at runtime
1.2. Adaptor
Convert the interface of a class to another interface that the client expects
Advantages
- Allows two or more incompatible objects to interact
- Reuse of older functionality
- Adapter class ‘adapts’ adaptee to target by committing a concrete adapter class
- Adapter is a subclass of adaptee
- Introduces only one object for adaption
- It will not work when a class and all its subclasses have to be ‘adapted’
- Object adapter has an instance variable of type Adaptee
- Single adapter works with all of adaptees sub-classes
- Makes it harder to override adaptee behavior
- Adapter is usually used to avoid changing existing classes [not an up-front design choice when both systems do not exist] Unlike Bridge pattern – both ends of adapter already exist and it glues them together
Example Vendor specific subclasses of an abstract DAO
1.3. Bridge
Decouple an abstraction from the implementation so that the two can vary independently
- Abstraction = Entity
- Implementation = Behavior
- Similar to Adapter – The Entity adapts the behavior to a different interface [Entity interface]
- Differs from Adapter – It is a design choice [both ends do not exist for Adapter
- Similar to Strategy and State in structure
- Differs from Strategy and State because these two design patterns have a single hierarchy of classes, so the behavior varies but the entity does not.
Advantages
- Two hierarchies of classes that vary independently
- The abstraction [entity] has-a implementation [behavior]
- Used rarely, often combines with AbstractFactory – [creating a family of products – Entity and Behavior]
- Hides implementation details from client
- Allows to assign and change behavior of entities at runtime
Disadvantages
- Behavior interface will be wide if the entities are highly orthogonal [Many varieties of operation]
- Delegation from Entities to Behaviors may degrade performance
- If a new entity is not satisfied with the current behavior interface, then changing interface needs extensive work
Example DAO Implements Bridge pattern to separate services
1.4. Builder
Separates the construction of a complex object from its representation so that the same construction process can create different representation
- Special case of strategy applied to create object
- Director has a fixed high-level procedure, but the actual construction process depends on what is being built. This construction process is encapsulated in a Strategy object called the Builder. E.g. Builder separates the push scheduler and data formatter for HTTP GET request
Advantages
- Lets you vary a products internal representation
- Isolates code for construction from representation
- Finer control over construction process
- Director constructs the object step by step
- Each step is implemented by a concrete builder
- Once all steps are done Director retrieves the result
Example
1.5. 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
Advantages
- Reduced coupling – Client need not know the receiver of request
- Added flexibility in assigning responsibilities to objects
Disadvantages
- Receipt of request is not guaranteed
- Chain may get lengthy and introduce performance problem
Example Commonly used for parsers
1.6. Command
Encapsulate a request as an object to parameterize clients with different requests, queue, or log requests and support undo operations
Advantages
- Easy to add new commands
- Can be assembled into composite commands
- Decouples the invoking object from the object that performs an operation
- Similar to Strategy – execute is the strategy method
- Differs to Strategy –
- command is a user triggered action
- Various commands can be unrelated – e.g. Strategy represents a single business rule such as tax calculations. All Strategies do the same thing in a different way e.g. State Tax calculation verses Federal Tax calculation
Disadvantages
Example
1.7. Composite
Compose objects into a tree structure to represent whole-part hierarchies
Advantages
- Lets clients treat individual objects and compositions of objects uniformly
- Defines hierarchies of primitive objects and composite objects
- Makes it easier to ass new kinds of components
Disadvantages
- Leaf has meaningless methods like add()
- Design could be made overly general, making it harder to restrict the components of a composite e.g. Make a composite have only certain components
- Type system will not enforce those contraints
Example Aggregate Entity Beans, XML DOM Model, Swing/AWT containers
1.8. Decorator
Attach additional responsibilities to an object dynamically
- Proxy is a special case of decorator pattern. Proxy is used with regard to security and networking and typically a class with a proxy cannot be accessed directly.
Advantages
- Modifies the behavior of individual objects without having to create a derived class and do this at run time
- More flexibility then static inheritance [ ‘has-a’ not ‘is-a’]
- Avoids feature laden classes high up in hierarchy
- Each feature is implemented in separate decorator class
Disadvantages
- A decorator and its component are not identical. So cannot rely on object identity when using this pattern
- It results in a lot of little objects composing the system
Example The java.io streams library implementation uses decorators to add responsibility to the stream
1.9. Façade
Unified interface to a set of interfaces in a system.
Advantages
- Reduces number of objects a client has to deal with
- Promotes weak coupling and less compilation dependencies
- Clients can still use subsystem classes [i.e. they do not have to go to the façade]
Example Session entity façade pattern in J2EE
1.10. Factory Method
Defines an interface to create an object but it lets the subclasses decide which class to instantiate
- A public creation method typically of the class that the method belongs to
Advantages
- Gives subclasses a hook for returning subclass
Disadvantages
- Have to subclass creator just to create a particular concrete product
Example EJBHome interface, Connection factories for EIS
1.11. Flyweight
Use sharing to support large number of fine grain objects efficiently
Advantages
- Key concept is distinct between intrinsic and extrinsic state – Intrinsic state is stored in the flyweight, Extrinsic state depends and varies with flyweight’s context and so cannot be shared
- Client objects are responsible for passing extrinsic state to flyweight
- Minimizes memory occupation by sharing as much data as possible with other similar objects
- Reduction in number of objects to handle
Disadvantages
Example Pooled EJBs, Pooled database connections
1.12. Interpreter
Given a language, defines a representation for its grammar along with an Interpreter that uses the representation to interpret sentences in the language
- Special case of Composite is applied to Parsing
Advantage
- Implementing grammar is easy
- Easy to change and Extend grammar
Disadvantages
- Complex grammars are hard to maintain. At least one class per rule.
Example
1.13. Iterator
Provide a way to access elements of aggregate object with out exposing its underlying representation.
Advantages
- Supports traversals of objects in a collection
- Variation in traversal achieved just by changing iterator
Example
1.14. Mediator
An object that encapsulates how a set of objects interact
Advantages
- Centralized control
- Loose coupling by preventing objects from referring each other
Example
1.15. Memento
Without violating encapsulation, capture and externalize an object’s internal state so that it can be restored to this state later
- Related to Command pattern regarding undo pattern
Advantages
- Preserves encapsulation boundaries
- Simplifies the originator [Object does not have to cache its own state as it changes]
Disadvantages
- Expensive if large data resides in Memento’s state
- It may be difficult in some languages to ensure only originator can access memento’s state
- Hidden cost of caring [and deleting] members
Example dfs
1.16. Observer
Defines a one-to-many dependency between objects, so that when one object changes state, all the dependents are notified and updated automatically
Advantages
- Abstract coupling between subject and observer
- Support for broadcast communication
Disadvantages
- Unexpected updates – Since observers are unaware of each other’s presence, they can be blind to the cost of changing the subject. A seemingly innocuous operation on the subject may cause a cascade of updates to observers and their dependent object
- Without additional protocol to help observers discover what changed, they may be forced to work hard to deduce what changed
Example Swing/AWT Listeners and Observers
1.17. Prototype
Specify the kind of object to instantiate using a prototypical instantiate using a prototypical instance and create new objects by copying this prototype
Advantages
- Add/remove concrete products just by registering a prototypical instance with a client
- Define new kinds of objects by instantiating existing classes and registering the instances as prototypes of client objects
- The client exhibits different behavior by delegating responsibility to the prototype
- Reduce sub-classing – Factory pattern often produces hierarchy of creator classes that parallels the product class hierarchy The prototype pattern allows cloning a prototype instead of using a factory method to create a new object
Example
1.18. Proxy
Provide a surrogate or place holder for another object to control access to it.
Advantages
- A remote proxy provides a local representation for an object in different address space
- A virtual proxy creates expensive objects on demand
- A protection proxy controls access to the original object
- A smart reference is a replacement for a bare pointer that performs additional actions when an object is accessed [e.g. counting number of references, loading persistent objects to memory on access, etc ]
Example EJB’s remote interface is a proxy for a bean
Proxy is used in RMI
1.19. Singleton
Control the number of instances of a class to a constant usually one and provide single global point of access.
Advantages
- Avoid polluting namespace with global variables
- More flexible than class variables or methods
Example Math class in Java
1.20. State
State pattern allows an object to alter its behavior when it’s internal state changes. The object will appear to change its class.
Advantages
- Localizes state specific behavior and partitions behavior for different states
- Makes state transition explicit – All variables of state change together in a single call.
- State objects can be shared like flyweights if states do not have instance variable [Type is a state]
- State objects are often singletons [Gof page 313]
- Similar to Strategy [& Command] – Single class/interface with many subclasses. The behavior is that of Strategy / Command design pattern
- Differs from Strategy [& Command] – Intend is different. Behavior is varied by changing state of object and not by performing[or invoking] a single action.
- Similar to Bridge – State is the implementation of behavior for abstract object
- Differs from Bridge – Bridge separates abstraction from implementation and is not based on the state of the object. Bridge pattern can implement any behavior on any instance of the abstraction
Example
1.21. Strategy
Defines a family of algorithms, encapsulates each one and makes them interchangeable [Alternative to sub classing – Context ‘has-a’ instead of a ‘is-a’ behavior]
Advantages
- Easier to extend a model to incorporate new behavior
Disadvantages
- Clients must be aware of an understand different strategies
- Increased number of objects
- Single interface for all strategies so simpler implementations may not need all the parameters given – Communication overhead.
Example
1.22. Template Method
Defines a skeleton of an algorithm in an operation deferring some steps to subclasses
- An alternative to Strategy when there are invariant parts of the algorithm
Advantages
- Fundamental technique for code reuse
- Inverted control structure [parent class calls subclass’s method]
Example The director in builder pattern may be implementing this pattern – only difference being Builders are not subclasses of Director
1.23. Visitor
It represents an operation to be performed on the elements of an object structure.
- Visitor lets us define a new operation without changing the classes of the elements on which it operates
- Each new operation is a subclass of the abstract Visitor
Advantages
- Visitor is after-the-fact substitute for multiple inheritance
- When an element is visited, it calls the visitor operation that corresponds to its class. The element supplies itself as an argument to this operation to let the visitor access its state
- Gathers related operations and separates unrelated ones. [Related operations in visitor and unrelated in their won visitor subclasses
- Visitor can visit objects that do not have same parent class
Disadvantages
- Adding new concrete elements is hard [needs new visitXXX method visitor] Consider whether it is most likely to change the algorithm [visitor] applied over an object structure or the classes that make up the structure
- Breaking encapsulation to allow visitor to access state
Example jaxb XJC implementation uses Visitor pattern
Tags: abstract factory, adapter, bridge, builder, cchain of responsibility, command, composite, decorator, Design Patterns, difference, facade, factory, factory method, fly weight, flyweight, gang of four, GoF, interpreter, iterator, mediator, memento, observer, prototype, proxy, similarity, singleton, state, stretegy, template method, visitor
Leave a comment