Oct, 16, 2007 1 Design Patterns PROBLEM CONTEXT SOLUTION A design pattern documents a proven...

93
Oct, 16, 2007 1 Design Patterns PROBLEM CONTEXT SOLUTION gn pattern documents a proven solution to a recurri m in a specific context and its consequences.
  • date post

    21-Dec-2015
  • Category

    Documents

  • view

    228
  • download

    0

Transcript of Oct, 16, 2007 1 Design Patterns PROBLEM CONTEXT SOLUTION A design pattern documents a proven...

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

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.

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

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

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

Oct, 16, 2007 3

Essential Elements

The pattern name The problem The solution The consequences

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

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

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

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

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

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.

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

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

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

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.

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

Oct, 16, 2007 9

Factory Method-Structure

Product

ConcreteProduct

Creator

FactortMethod()AnOperation()

ConcreteCreator

FactoryMethod()

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

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.

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

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.

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

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.

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

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

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

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.

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

Oct, 16, 2007 15

Abstract Factory-Structure

AbstractFactory

CreateProductA()CreateProductB()

ConcreteFactory1

CreateProductA()CreateProductB()

ConcreteFactory2

CreateProductA()CreateProductB()

AbstractProductA

ProductA2 ProductA1

AbstractProductB

ProductB2 ProductB1

Client

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

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.

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

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.

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

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.

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

Oct, 16, 2007 19

Abstract Factory-Implementation

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

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

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.

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

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.

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

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.

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

Oct, 16, 2007 23

Builder-Structure

Directorconstruct()

BuilderBuildPart()

+builder

ConcreteBuilderBuildPart()GetResult()

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

Product

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

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.

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

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.

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

Oct, 16, 2007 26

Implementation

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

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

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.

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

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.

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

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.

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

Oct, 16, 2007 30

Structure

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

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.

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

Oct, 16, 2007 32

Implementation

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

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

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.

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

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.

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

Oct, 16, 2007 35

Class Adapter- Structure

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

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

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

Oct, 16, 2007 37

Object Adapter-Structure

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

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

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

Oct, 16, 2007 39

Bridge

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

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

Oct, 16, 2007 40

Structure

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

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.

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

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.

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

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

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

Oct, 16, 2007 44

Structure

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

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.

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

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.

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

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

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

Oct, 16, 2007 48

Structure

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

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

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

Oct, 16, 2007 50

FAÇADE-Object Structural

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

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

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

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

Oct, 16, 2007 52

Structure

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

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.

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

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.

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

Oct, 16, 2007 55

Structure

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

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.

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

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.

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

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.

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

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.

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

Oct, 16, 2007 60

Structure

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

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

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

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

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

Oct, 16, 2007 63

Structure

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

Oct, 16, 2007 64

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

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

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

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.

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

Oct, 16, 2007 67

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

Oct, 16, 2007 68

Consequences

It limits subclassing. It decouples colleagues. It simplifies object protocols. It abstracts how objects cooperate. It centralizes control.

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

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.

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

Oct, 16, 2007 70

Structure

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

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.

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

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.

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

Oct, 16, 2007 73

Structure

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

Oct, 16, 2007 74

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

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.

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

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.

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

Oct, 16, 2007 77

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

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.

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

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.

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

Oct, 16, 2007 80

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

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.

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

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.

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

Oct, 16, 2007 83

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

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.

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

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.

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

Oct, 16, 2007 86

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

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.

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

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

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

Oct, 16, 2007 89

Structure

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

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.

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

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)

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

Oct, 16, 2007 92

Structure

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

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.