View
227
Download
0
Tags:
Embed Size (px)
Citation preview
Oct, 16, 2007 1
Design Patterns
PROBLEM
CONTEXT
SOLUTION
A design pattern documents a proven solution to a recurring problem in a specific context and its consequences.
Oct, 16, 2007 2
References
1. Design Patterns, Elements of Reusable Object-Oriented Software, – Erich Gamma
– Richard Helm
– Ralph Johnson
– John Vlissides
– Addison-Wesley
2. Java Design Patterns: A tutorial– James W. Cooper
Oct, 16, 2007 3
Essential Elements
The pattern name The problem The solution The consequences
Oct, 16, 2007 4
Describing Design Patterns
Pattern Name and Classifications
Intent Also Known As Motivation Applicability Structure
Participants Collaborations Consequences Implementation Sample Code Known Uses Related Patterns
Oct, 16, 2007 5
The Catalog of Design Patterns
Creational Structural BehavioralInterpreterTemplate Method
Abstract Factory Adaptor Chain of ResponsibilityBuilder Bridge CommandPrototype Composite IteratorSingleton Decorator Mediator
Façade MementoFlyweight ObserverProxy State
StrategyVisitor
Purpose
Scope Class
Object
Factory Method Adaptor
Oct, 16, 2007 6
Creational Patterns
Abstract the instantiation process Make system independent of how its object are
created, composed, and represented. Creational class patterns use inheritance to vary
the class that’s instantiated.– Factory Method
Creational object patterns delegate instantiation to another object.– Abstract Factory, Builder, Prototype, Singleton.
Oct, 16, 2007 7
Factory Method-Class Creational
Intent: define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Also Known As: Virtual Constructor
Oct, 16, 2007 8
Factory Method-Applicability
A class can’t anticipate the class of objects it must create.
A class wants its subclasses to specify the objects it creates.
Classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.
Oct, 16, 2007 9
Factory Method-Structure
Product
ConcreteProduct
Creator
FactortMethod()AnOperation()
ConcreteCreator
FactoryMethod()
Oct, 16, 2007 10
Factory Method-Participants
Product:defines the interface of objects the factory method creates.
ConcreteProduct: implements the Product interface Creator: declares the factory method, which returns
an object of type Product. Creator may also define a default implementation of the factory method that returns default ConcreteProduct object; may call the factory method to create a Product object.
ConcreteCreator: overrides the factory method to return an instance of a ConcreteProduct.
Oct, 16, 2007 11
Factory Method
Collaborations – Creator relies on its subclasses to define the
factory method so that it returns an instance of the appropriate ConcreteProduct.
Consequences– Provide hooks for subclasses.– Connects parallel class hierarchies.
Oct, 16, 2007 12
Factory Method-Implementation
Two major varieties: (1) when the Creator class is an abstract class and does not provide an implementation for the factory method it declares; (2)when the Creator is a concrete class and provides a default implementation for the factory method.
Parameterized factory methods. Language-specific variants and issues. Using templates to avoid subclassing. Naming conventions.
Oct, 16, 2007 13
Abstract Factory Object Creational
Intent: provide an interface for creating families of related or dependent objects without specifying their concrete classes.
Also Known As: kit Motivation: ..
Oct, 16, 2007 14
Abstract Factory-Applicability
A system should be independent of how its products are created, composed, and represented.
A system should be configured with one of multiple families of products.
A family of related product objects is designed to be used together, and you need to enforce this constraint.
You want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.
Oct, 16, 2007 15
Abstract Factory-Structure
AbstractFactory
CreateProductA()CreateProductB()
ConcreteFactory1
CreateProductA()CreateProductB()
ConcreteFactory2
CreateProductA()CreateProductB()
AbstractProductA
ProductA2 ProductA1
AbstractProductB
ProductB2 ProductB1
Client
Oct, 16, 2007 16
Abstract Factory-Participants
AbstractFactory: declares an interface for operations that create abstract product objects.
ConcreteFactory: implements the operations to create concrete product objects.
AbstractProduct: declares an interface for a type of product object.
ConcreteProduct: 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.
Oct, 16, 2007 17
Abstract Factory-Collaborations
Normally a single instance of a ConcreteFactory class is created at run-time.This concrete factory creates product objects having a particular implementation. To create different product objects, clients should use a different concrete factory.
AbstractFactory defers creation of product objects to its ConcreteFactory subclass.
Oct, 16, 2007 18
Abstract Factory-Consequences
It isolates concrete classes. It makes exchanging product families easy. It promotes consistency among products. Supporting new kinds of products is
difficult.
Oct, 16, 2007 19
Abstract Factory-Implementation
Factories as singletons. Creating the products. Defining extensible factories.
Oct, 16, 2007 20
Singleton-Object Creational
Intent: Ensure a class only has one instance, and provide a global point of access to it.
Applicability– There must be exactly one instance of a class, and it
must be accessible to clients from a well-known access point.
– When the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.
Oct, 16, 2007 21
Consequences
Controlled access to sole instance. Reduced name space. Permits refinement of operations and
representation. Permits a variable number of instances. More flexible than class operation.
Oct, 16, 2007 22
Builder-Object Creational
Intent: Separate the construction of a complex object from its representation so that the same construction process can create different representations.
Applicability: when– The algorithm for creating a complex object should be
independent of the parts that make up the object and how they are assembled.
– The construction process must allow different representations for the object that is constructed.
Oct, 16, 2007 23
Builder-Structure
Directorconstruct()
BuilderBuildPart()
+builder
ConcreteBuilderBuildPart()GetResult()
for all objects in struct ture {builder->BuildPart()}
Product
Oct, 16, 2007 24
-Participants
Builder: specifies an abstract interface for creating parts of a Product object.
ConcreteBuilder:– Constructs and assembles parts of the product by implementing
the Builder interface.– Defines and keeps track of the representing it creates.– Provides an interface for retrieving the product.
Director: constructs an object using the Builder interface.
Product– Represents the complex object under construction.
ConcreteBuilder builds the product’s internal representation and defines the process by which it’s asembled.
– Includes classes that define the constituent parts, including interfaces for assembling the parts into the final results.
Oct, 16, 2007 25
Consequences
It lets you vary a product’s internal representation.
It isolates code for construction and representation.
It gives you finer control over the construction process.
Oct, 16, 2007 26
Implementation
Assembly and construction interface. Why no abstract class for products? Empty methods as default in Builder.
Oct, 16, 2007 27
Prototype-Object Creational
Intent: Specifies the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
Oct, 16, 2007 28
Prototype
Applicability:– When the classes to instantiate are specified at run-
time, for example, by dynamic binding; and
– To avoid building a class hierarchy of factories that parallels the class hierarchy of products; or
– When instances of a class can have one of only a few different combinations of state. It may be more convenient to install a corresponding number of prototypes and clone them rather than instantiating the class manually, each time with the appropriate state.
Oct, 16, 2007 29
Participants
Prototype– Declares an interface for cloning itself.
ConcretePrototype– Implements an operation for cloning itself.
Client– Creaets a new object by asking a prototype to
clone itself.
Oct, 16, 2007 30
Structure
Oct, 16, 2007 31
consequences
Adding and removing products at run-time. Specifying new objects by varying values. Specifying new objects by varying
structure. Reduced subclassing Configuring an application with classes
dynamically.
Oct, 16, 2007 32
Implementation
Using a prototype manager. Implementing the Clone operation. Initializing clones.
Oct, 16, 2007 33
Structural Patterns
Focus on how classes and objects are composed to form larger structures.
Structural class patterns use inheritance to compose interfaces or implementations, while structural object patterns describe ways to compose objects to realize new functionality.
Oct, 16, 2007 34
Adapter-Class, Object Structural
Intent: Convert the interface of a class into another interface client expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
Oct, 16, 2007 35
Class Adapter- Structure
Oct, 16, 2007 36
Class Adapter Applicability
– You obtain a target class, which you need to use in your designs, but, the public interface of the target class (it’s methods) does not match your requirements or it does not fit into the necessary class inheritance hierarchy.
Solution– Create an abstract interface ancestor class that implements the interchangeable interface
that clients expect – Create an adapter subclass of the interface class. – Multiply inherit the adapter class from the target class to automatically include both its
implementation. – Override the methods from the interface class in the adapter class to call the methods in
the target class. Consequences
– The Adapter may optionally override behavior in the Target class. – Minimizes the number of new objects required – The Adapter class may also be used in designs which expect a Target class. – Cannot be used to adapt Target and its subclasses. Only the Target class itself can be
adapted. – This technique cannot be used in languages that do not support multiple inheritance
Oct, 16, 2007 37
Object Adapter-Structure
Oct, 16, 2007 38
Object Adapter Applicability
– You obtain a target class that you need to use in your designs, but, the public interface of the target class (it’s methods) does not match your requirements or it does not fit into the necessary class inheritance hierarchy.
Solution– Create an abstract interface ancestor class that implements the interchangeable
interface that clients expect – Create an adapter subclass of the interface class – The constructor or other appropriate method in the adapter class will construct an
instance of the target class (as appropriate). – Each method in the adapter class call the appropriate method(s) in the target class
as needed to implement the expected functionality. Consequences
– Lets a single adapter work with many targets (e.g. the target and all it’s subclasses, if any).
– Makes it harder to override the target’s behavior. The target must be subclassed and the adapter must be modified to use the subclass
Oct, 16, 2007 39
Bridge
Intent: Decouple an abstraction from its implementation so that the two can vary independently.
Oct, 16, 2007 40
Structure
Oct, 16, 2007 41
Implementation
Create an Implementation class which defines a public interface.
Create subclasses of the Implementation class to implement each operation as needed.
Create an Abstraction class which maintains an association to the Implementation class and provides a set of functions to invoke those operations.
For each client class that needs to use an Implementation subclass, subclass the client from the Abstraction.
Oct, 16, 2007 42
Consequences
Avoids permanent bindings between an abstraction and its implementation.
Both abstractions and implementations are extensible via subclassing.
Changes to the implementation have little or no impact on clients.
Hides implementation of an abstraction from clients.
Allows sharing an implementation among multiple objects and hiding that fact from clients.
Oct, 16, 2007 43
Composite-Object Structural
Intent: Compose objects into tree structures to represent whole-part hierarchies in a manner that lets clients treat objects and compositions uniformly.
Applicability– You want to represent whole-part hierarchies. – You don’t want clients to know the difference
between compositions (nodes) and individual (leaf) objects
Oct, 16, 2007 44
Structure
Oct, 16, 2007 45
Implementation
Create an abstract Component class which defines the interface of all tree objects and implements default common behavior.
Subclass Component to create a concrete Composite class which implements behavior for storing and accessing child Component objects.
Subclass Component to create each individual child (leaf) object.
Oct, 16, 2007 46
Consequences A near pure implementation of 1:N Recursive Connection, thus gains
its advantages (and drawbacks, of course!) Provides definitions of primitive class hierarchies that may easily be
composed into recursive layers of more complex types with out affecting clients. This satisfies the Open/Closed principle nicely.
Clients code need not have any knowledge of the specific class of an object to call its operations methods on either individual objects or composites. (Liskov Substitution). However, this is not true for the Add, Remove and GetChild methods (see below).
May make a design overly general due to the difficulty of restricting Leaf objects. The public interface of Component makes this design almost like a Recursive Unification.
Design may violate Liskov Substitution due to possible client calls to the Add, Remove and GetChild methods for a Leaf object. If client calls these function in a leaf object, an error may result. Thus the client might need to implement special processing.
Oct, 16, 2007 47
Decorator-Object Structural
Intent: Attach additional responsibilities or alternate processing to an object dynamically.
Applicability:– You need to add or vary the responsibilities of an
object based on wider system actions or changes – You need to easily remove a responsibility – When subclassing responsibilities would create an
explosion of classes – Often used in GUIs to wrap visual “decorations”
(scrollbars, frames, etc.) around windows and widgets
Oct, 16, 2007 48
Structure
Oct, 16, 2007 49
Consequences Allows building flexible combinations and variations of
responsibilities due to its strong basis on 1:1 Recursive Connection. Client classes need not have any knowledge of a decorator’s specific
operation to use it. (Liskov Substitution). Separates public interface from implementation and moves code down
and across a shallow inheritance hierarchy (Dependency Inversion) Properties may added more than once, which may be bad or good,
depending on requirements If clients need to use a specific decorator’s interface, downcasting may
be required, thus violating Liskov Substitution Often results in systems with large numbers of small classes which
seem to look alike. This can make it harder to find specific classes. Good documentation is required to explain the design (the design pattern simplifies this chore!)
Oct, 16, 2007 50
FAÇADE-Object Structural
Intent: Encapsulate a subsystem using a high-level interface, simplifying subsystem usage and hiding structural details.
Oct, 16, 2007 51
Implementation
Clients communicate with subsystem objects by calling methods in Façade
Clients never (or as seldom as possible) directly accessing objects in subsystem -- any such access weakens the encapsulation.
Subsystem objects usually retain no knowledge of client
Subsystem objects do not normally maintain any reference to Façade
Oct, 16, 2007 52
Structure
Oct, 16, 2007 53
Consequences
Eliminates hard to control tangled networks of object associations
Reduces number of objects clients need to interface with.
Promotes weak coupling, which enhances overall flexibility.
Oct, 16, 2007 54
PROXY-Object Structural
Intent: Provide a surrogate or place holder to control access to an object.
Implementation:– Create an abstract Subject class that defines the
complete public interface of an object, but does not implement it.
– Derive a RealSubject class from Subject and implement the public interface as needed to perform all required behavior.
– Derive a ProxySubject which creates the RealSubject and passes all requests to it.
Oct, 16, 2007 55
Structure
Oct, 16, 2007 56
Consequences
Proxy is extremely good for patching inflexible OO designs in a well-controlled manner, often adding flexibility to the design.
Proxies can be used to distribute objects to different object spaces or across networks
ProxySubject can enhance RealSubject’s behavior -- particularly important when used to encapsulate 3rd party libraries.
Oct, 16, 2007 57
Flyweight
Intent: Use sharing to support large numbers of fine-grained object efficiently.
Applicability:– An application uses a large number of objects– Storage costs are high because of the sheer quantity of
objects.– Most object state can be made extrinsic.– Many groups of objects may be replaced by relatively
few shared objects once extrinsic state is removed.– The application doesn’t depend on object identity.
Oct, 16, 2007 58
Behavioral
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.
Oct, 16, 2007 59
Template Method
Intent– Let a descendant redefine certain tasks without
modifying the basic algorithm defined by an ancestor method.
Solution– Break out primitive steps into separate methods in
ancestor class. – Construct method for basic algorithm in ancestor that
calls the primitive methods. – Override the primitive methods in descendant classes to
implement specific tasks.
Oct, 16, 2007 60
Structure
Oct, 16, 2007 61
Consequences
A fundamental technique for code reuse -- particularly important in class libraries and frameworks to factor out common behavior.
Leads to inverted control structure called ‘Hollywood Principle’ (don’t call us, we’ll call you.)
A primitive method in the ancestor may provide a default behavior that descendants may optionally override (called hook methods.)
Oct, 16, 2007 62
Observer
Intent: – Define relationship between a group of objects such
that whenever one object is updated all others are notified automatically.
Applicability– Changes to one object in a group requires changes to
the others in the group – The number of objects in the group may vary – Loose coupling is desired between the objects in the
group
Oct, 16, 2007 63
Structure
Oct, 16, 2007 64
Oct, 16, 2007 65
Consequences Subjects have limited knowledge of the objects in
the observed group Objects may easily be added or removed without
changing existing objects Update notifications are automatically broadcast
to all interested objects The cost of updating any object in the group may
greater than expected Update notifications may occur more frequently
than desired or expected
Oct, 16, 2007 66
Mediator
Intent: 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.
Applicability:– A set of objects communicate in well-defined but
complex ways.– Reusing an object is difficult because it refers to and
communicates with many other objects.– A behavior that’s distributed between several classes
should be customizable without a lot of subclassing.
Oct, 16, 2007 67
Oct, 16, 2007 68
Consequences
It limits subclassing. It decouples colleagues. It simplifies object protocols. It abstracts how objects cooperate. It centralizes control.
Oct, 16, 2007 69
Chain of Responsibility Intent: Avoid coupling the sender of a request to
its receiver by giving more than one object a chance to handle the request.
Applicability:– More than one object may handle a request and the
specific handler needs to be ascertained automatically – A request needs to be issued to a set objects that
changes at run-time – You want to avoid any specific knowledge by the client
of the available request handlers in the system Implementation: Chain the receiver objects in a
linked list and pass the request along the chain until an object handles it.
Oct, 16, 2007 70
Structure
Oct, 16, 2007 71
Consequences
Reduces coupling between a client and its responsibilities. New or alternate responsibilities can be easily added at runtime
Clients have no explicit knowledge of specific Receivers since it knows only an abstraction (Dependency Inversion Principle)
The abstract Receiver class is usually small, stable and not highly susceptible to change, thus it is “closed” (Open/Closed Principle)
There is no guarantee that any particular request may be actually handled, since it’s possible no handler in the chain can process it.
Clients are responsible to pass the request along the chain, calling each object in turn. If many clients exist, this will lead to code duplication and violates the Law of Demeter.
Oct, 16, 2007 72
COMMAND Intent: Encapsulate a request as a parameterized
object; allow different requests, queue or log requests and support undoable operations.
Applicability:– Parameterize objects by an action to perform.– Specify, queue, and execute requests at different times.– Support undo.– Support logging changes so that they can be reapplied in
case of a system crash.– Structure a system around high-level operations built on
primitives operations.
Oct, 16, 2007 73
Structure
Oct, 16, 2007 74
Oct, 16, 2007 75
Consequences
Decouples an object from the operations performed on it.
Assemble commands into a composite command.
It’s easy to add new commands.
Oct, 16, 2007 76
State
Intent: allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
Applicability:– An object’s behavior depends on its state, and it
must change its behavior at run-time depending on that state.
– Operations have large, multipart conditional statements that depend on the object’s state.
Oct, 16, 2007 77
Oct, 16, 2007 78
Consequences
It localizes state-specific behavior and partitions behavior for different states.
It makes state transitions explicit. State objects can be shared.
Oct, 16, 2007 79
Memento
Intent: without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later.
Applicability:– A snapshot of an object’s state must be saved so that it
can be restored to that state later, and
– A direct interface to obtaining the state would expose implementation details and break the object’s encapsulation.
Oct, 16, 2007 80
Oct, 16, 2007 81
Consequences
Preserving encapsulation boundaries. It simplifies originator. Using mementos might be expensive. Defining narrow and wide interfaces. Hidden costs in caring for mementos.
Oct, 16, 2007 82
Strategy
Intent: define a family of algorithms, encapsulate each one, and make them interchangeable.
Applicability– Many related classes differ only in their behavior.
– You need different variants of an algorithm.
– An algorithm uses data that clients shouldn’t know about.
– A class defines many behaviors, and these appear as multiple conditional statements in its operation.
Oct, 16, 2007 83
Oct, 16, 2007 84
Consequences
Families of related algorithms. An alternative to subclassing. Strategies eliminate conditional statements. A choice of implementations. Clients must be aware of different strategies. Communication overhead between strategy and
context. Increased number of objects.
Oct, 16, 2007 85
Visitor Intent: 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.
Applicability:– An object structure contains many classes of objects
with differing interfaces, and you want to perform operations on these objects that depend on their concrete classes.
– Many distinct and unrelated operations need to perform on objects in an object structure.
– The classes defining the object structure rarely change, but you often want to define new operations over the structure.
Oct, 16, 2007 86
Oct, 16, 2007 87
Consequences
Visitor makes adding new operations easy. A visitor gathers related operations and
separates unrelated ones. Adding new ConcreteElement classes is
hard. Visiting across class hierarchies. Accumulating state. Breaking encapsulation.
Oct, 16, 2007 88
Interpreter
Intent: given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
Applicability: – The grammar is simple– Efficiency is not a critical concern
Oct, 16, 2007 89
Structure
Oct, 16, 2007 90
Consequences
It’s easy to change and extend the grammar. Implementing the grammar is easy. Complex grammars are hard to maintain. Adding new ways to interpret expressions.
Oct, 16, 2007 91
Iterator
Intent: provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
Applicability:– To access an aggregate object’s contents without
exposing its internal representation.
– To support multiple traversals of aggregate objects
– To provide a uniform interface for traversing different aggregate structures (polymorphic iteration)
Oct, 16, 2007 92
Structure
Oct, 16, 2007 93
Consequences
It supports variations in the traversal of an aggregate.
Iterators simplify the Aggregate interface. More than one traversal can be pending on
an aggregate.