nov, 1, 2005 1 design patterns problem context solution a design pattern documents a proven solution...

75
Nov, 1, 2005 1 Design Patterns PROBLEM CONTEXT SOLUTION gn pattern documents a proven solution to a recurri m in a specific context and its consequences.

Post on 20-Dec-2015

214 views

Category:

Documents


0 download

TRANSCRIPT

Nov, 1, 2005 1

Design Patterns

PROBLEM

CONTEXT

SOLUTION

A design pattern documents a proven solution to a recurring problem in a specific context and its consequences.

Nov, 1, 2005 2

Essential Elements

The pattern name The problem The solution The consequences

Nov, 1, 2005 3

Describing Design Patterns

Pattern Name and Classifications

Intent Also Known As Motivation Applicability Structure

Participants Collaborations Consequences Implementation Sample Code Known Uses Related Patterns

Nov, 1, 2005 4

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

Nov, 1, 2005 5

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.

Nov, 1, 2005 6

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

Nov, 1, 2005 7

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.

Nov, 1, 2005 8

Factory Method-Structure

Product

ConcreteProduct

Creator

FactortMethod()AnOperation()

ConcreteCreator

FactoryMethod()

Nov, 1, 2005 9

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.

Nov, 1, 2005 10

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.

Nov, 1, 2005 11

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.

Nov, 1, 2005 12

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: ..

Nov, 1, 2005 13

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.

Nov, 1, 2005 14

Abstract Factory-Structure

AbstractFactory

CreateProductA()CreateProductB()

ConcreteFactory1

CreateProductA()CreateProductB()

ConcreteFactory2

CreateProductA()CreateProductB()

AbstractProductA

ProductA2 ProductA1

AbstractProductA

ProductA2 ProductA1

Client

Nov, 1, 2005 15

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.

Nov, 1, 2005 16

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.

Nov, 1, 2005 17

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.

Nov, 1, 2005 18

Abstract Factory-Implementation

Factories as singletons. Creating the products. Defining extensible factories.

Nov, 1, 2005 19

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.

Nov, 1, 2005 20

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.

Nov, 1, 2005 21

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.

Nov, 1, 2005 22

Builder-Structure

Directorconstruct()

BuilderBuildPart()

+builder

ConcreteBuilderBuildPart()GetResult()

for all objects in struct ture {builder->BuildPart()}

Product

Nov, 1, 2005 23

-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.

Nov, 1, 2005 24

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.

Nov, 1, 2005 25

Implementation

Assembly and construction interface. Why no abstract class for products? Empty methods as default in Builder.

Nov, 1, 2005 26

Prototype-Object Creational

Intent: Specifies the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

Nov, 1, 2005 27

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.

Nov, 1, 2005 28

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.

Nov, 1, 2005 29

Structure

Nov, 1, 2005 30

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.

Nov, 1, 2005 31

Implementation

Using a prototype manager. Implementing the Clone operation. Initializing clones.

Nov, 1, 2005 32

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.

Nov, 1, 2005 33

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.

Nov, 1, 2005 34

Class Adapter- Structure

Nov, 1, 2005 35

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

Nov, 1, 2005 36

Object Adapter-Structure

Nov, 1, 2005 37

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

Nov, 1, 2005 38

Bridge

Intent: Decouple an abstraction from its implementation so that the two can vary independently.

Nov, 1, 2005 39

Structure

Nov, 1, 2005 40

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.

Nov, 1, 2005 41

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.

Nov, 1, 2005 42

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

Nov, 1, 2005 43

Structure

Nov, 1, 2005 44

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.

Nov, 1, 2005 45

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.

Nov, 1, 2005 46

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

Nov, 1, 2005 47

Structure

Nov, 1, 2005 48

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!)

Nov, 1, 2005 49

FAÇADE-Object Structural

Intent: Encapsulate a subsystem using a high-level interface, simplifying subsystem usage and hiding structural details.

Nov, 1, 2005 50

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

Nov, 1, 2005 51

Structure

Nov, 1, 2005 52

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.

Nov, 1, 2005 53

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.

Nov, 1, 2005 54

Structure

Nov, 1, 2005 55

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.

Nov, 1, 2005 56

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.

Nov, 1, 2005 57

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.

Nov, 1, 2005 58

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.

Nov, 1, 2005 59

Structure

Nov, 1, 2005 60

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.)

Nov, 1, 2005 61

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

Nov, 1, 2005 62

Structure

Nov, 1, 2005 63

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

Nov, 1, 2005 64

Mediator

Intent: define an object that encapsulates how aset of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction indecently.

Applicability:– A set of objects communicate in well-defined but

comple 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.

Nov, 1, 2005 65

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.

Nov, 1, 2005 66

Structure

Nov, 1, 2005 67

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.

Nov, 1, 2005 68

COMMAND-Object Behavioral

Intent: Encapsulate a request as a parameterized object; allow different requests, queue or log requests and support undoable operations.

Implementation:– Client creates commands as needed, specifying the Receiver

object and parameters the command will use to execute later. – Each SpecificCommand is inherited from a common abstract

class which defines the basic execute interface Invoker uses to trigger commands when needed.

– Each SpecificCommand knows the Receiver it works with and the parameters it needs to perform its encapsulated action by calling methods in its associated Receiver.

Nov, 1, 2005 69

Structure

Nov, 1, 2005 70

Consequences

Decouples an object from the operations performed on it.

Nov, 1, 2005 71

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.

Nov, 1, 2005 72

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.

Nov, 1, 2005 73

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.

Nov, 1, 2005 74

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.

Nov, 1, 2005 75

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

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