132
基基 UML 基基基基基基 基基基基基 Lecture 10 Design Pattern

基于 UML 的面向对象系统分析与设计

Embed Size (px)

DESCRIPTION

基于 UML 的面向对象系统分析与设计. Lecture 10 Design Pattern. Books. Design Patterns : Elements of Reusable Object-Oriented Software (1995) The-Gang-of-Four (GoF) - Gamma, Helm, Johnson , Vlissides Analysis Patterns - Reusable Object Models Martin Fowler The Design Patterns Smalltalk Companion - PowerPoint PPT Presentation

Citation preview

Page 1: 基于 UML 的面向对象系统分析与设计

基于 UML的面向对象系统分析与设计

Lecture 10 Design Pattern

Page 2: 基于 UML 的面向对象系统分析与设计

Books

Design Patterns : Elements of Reusable Object-Oriented Software (1995) The-Gang-of-Four (GoF) - Gamma, Helm, Johnson ,

Vlissides Analysis Patterns - Reusable Object Models

Martin Fowler The Design Patterns Smalltalk Companion

Alpert, Brown & Woolf

Page 3: 基于 UML 的面向对象系统分析与设计

Design Patterns

“Each pattern describes

a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice”.

--- Christopher Alexander, 1977

This was in describing patterns in buildings and towns.In SE, design patterns are in terms of objects and interfaces,

not walls and doors.

The manner in which a collection of interacting objects collaborate to accomplish a specific task or provide some specific functionality.

Page 4: 基于 UML 的面向对象系统分析与设计

Essential Elements of Design Patterns

– Name: identifies a pattern– Problem: describes when to apply the pattern in terms of the

problem and context– Solution: describes elements that make up the design, their

relationships, responsibilities, and collaborations– Consequences: results and trade-offs of applying the pattern

Page 5: 基于 UML 的面向对象系统分析与设计

How to Describe Design Patterns more fully

A format for design patterns Pattern Name and Classification Intent Also Known As Motivation Applicability Structure Participants Collaborations Consequences Implementation Sample Code Known Uses Related Patterns

This is critical because the information has to be conveyed to peer This is critical because the information has to be conveyed to peer developers in order for them to be able to evaluate, select and utilize developers in order for them to be able to evaluate, select and utilize patterns.patterns.

Page 6: 基于 UML 的面向对象系统分析与设计

Organizing Design Patterns

• By Purpose (reflects what a pattern does):– Creational Patterns– Structural Patterns– Behavioral Patterns

• By Scope: specifies whether the pattern applies primarily to classes or to

objects.

Page 7: 基于 UML 的面向对象系统分析与设计

Design Patterns Space

Abstract FactoryBuilderPrototypeSingleton

AdapterBridgeCompositeDecoratorFaçadeFlyweightProxy

Chain of ResponsibilityCommandIteratorMediatorMementoObserverStateStrategyVisitor

Factory Method AdapterInterpreterTemplate

Creational Structural Behavioral

Object

ClassScope

Purpose

Page 8: 基于 UML 的面向对象系统分析与设计

Some Design Patterns

Pattern Name Role

Adapter Convert the interface of one class into another interfaceclients expect. Adapter allows classes to work togetherthat otherwise can’t because of incompatible interfaces.

Proxy Provide a surrogate or placeholder for another object.

Mediator Define an object that encapsulates how a set ofobjects interact. Mediator promotes loose coupling bykeeping objects from referring to each other explicitlyand let one vary its interaction independently

Observer Define a one-to-many dependency betweenobjects so that when one object changes state, allits dependents will be notified and updated automatically.

Template Define the skeleton of an algorithm in anoperation, deferring some steps to subclasses.

Page 9: 基于 UML 的面向对象系统分析与设计

Creational Patterns

• Creational Patterns– Abstract Factory, Factory Method, Singleton– Concerned with object creation– Who creates what, when and how

Page 10: 基于 UML 的面向对象系统分析与设计

Structural Patterns

• Structural Patterns– Concerned with the composition of classes or

objects– Structural class patterns use inheritance to

compose interfaces or implementations.– Structural object patterns describe ways to

compose objects to realize new functionality.

Page 11: 基于 UML 的面向对象系统分析与设计

Behavioral Patterns

• Behavioral Patterns– Characterize the ways in which classes or

objects interact and distribute responsibility– Behavioral patterns are concerned with

algorithms and the assignment of responsibilities between objects.

– Behavioral patterns also describe patterns of communication between objects and classes.

Page 12: 基于 UML 的面向对象系统分析与设计

Sample - Adapter Pattern

Structural Pattern

Page 13: 基于 UML 的面向对象系统分析与设计

8 Adapter• Intermediary acts like a translator between the

client and the server.

Client AdapterAdapter Server

Page 14: 基于 UML 的面向对象系统分析与设计

Example

• Requirements Change– Add Triangle object

Page 15: 基于 UML 的面向对象系统分析与设计

Example

• Suppose XTriangle class has already existed– Xdraw– Xgetarea

• Solutions:– Create class Triangle derives from Shape– Triangle contains Xtriangle (composition

relationship)– Triangle passes requests made to the Triangle

object on through to the XTriangle object

Page 16: 基于 UML 的面向对象系统分析与设计

ExampleClass Triangle extends Shape{ … private XTriangle tgl … public Triangle(){ tgl=new XTriangle(); } void public draw(){ tgl.Xdraw(); }}

Page 17: 基于 UML 的面向对象系统分析与设计

Adapter

Client

Adapter

+request()

Adaptee

+specificOperation()

Target

+request()

adaptee.specificOperation()

Class Diagram

Canvas Shape

Triangle

XTriangle

Xtriangle.Xdraw()

Page 18: 基于 UML 的面向对象系统分析与设计

Adapter• Intent:

– Match an existing object beyond your control to a particular interface.• Problem:

– A system has the right data and behavior but the wrong interface. Typical used when you have to make something a derivative of an abstract class we are defining or already have.

• Solution:– The adapter provides a wrapper with the desired interface.

• Participants and Collaborators:– The Adapter adapts the interface of an Adaptee to match that of Adapter’s Target(the

class it derives from). This allows the Client to use the Adaptee as if it were a type of Target.

• Consequences:– The Adapter pattern allows for preexisting objects to fit into new class structures without

being limited by their interfaces.• Implementation:

– Contain the existing class in another class. Have the containing class match the required interface and call the methods of the contained class.

Page 19: 基于 UML 的面向对象系统分析与设计

Adapter

• Target — defines the domain-specific interface that the client uses.• Client — collaborates with objects conforming to the Target interface.• Adaptee — defines an existing interface that needs adapting.• Adapter — adapts the interface of Adaptee to the Target interface.

Participants

Clients call operations on an Adapter instance. In turn, the Adapter calls Adaptee operations that carry out the request.

Collaborations

Page 20: 基于 UML 的面向对象系统分析与设计

• Name: Adapter • Intent: Convert the interface of a class into another

interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

• Motivation: Sometimes a toolkit class that's designed for reuse isn't reusable only because its interface doesn't match the domain-specific interface an application requires.

Adapter Summery

Page 21: 基于 UML 的面向对象系统分析与设计

Adapter Summery

• Applicability – use the Adapter when:– You want to use an existing class, and its interface does

not match the one you need.– You want to create a reusable class that cooperates with

unrelated or unforeseen classes, that is, classes that don’t necessarily have compatible interfaces.

– (object adapter only) you need to use several existing subclasses, but it’s impractical to adapt their interface by subclassing every one. An object adapter can adapt the interface of its parent class.

Page 22: 基于 UML 的面向对象系统分析与设计

Task• Creational Pattern

– Singleton– Abstract Factory– Factory Method

• Structural Pattern– Bridge– Facade– Decorator

• Behavioral Pattern– Strategy– Observer– Template Method

• ……..

Page 23: 基于 UML 的面向对象系统分析与设计

MORE… FYI

Page 24: 基于 UML 的面向对象系统分析与设计

Singleton Pattern

Creational Pattern

Page 25: 基于 UML 的面向对象系统分析与设计

Singleton Pattern

• The Singleton pattern ensures that a class has only one instance and provides a global point of access to it.

• Examples: – There can be many printers in a system but there

should only be one printer spooler.– There should be only one instance of a

WindowManager.– There should be only one instance of a filesystem.

Page 26: 基于 UML 的面向对象系统分析与设计

Singleton Pattern

• How do we ensure that a class has only one instance and that the instance is easily accessible?

• A global variable makes an object accessible, but does not keep you from instantiating multiple objects.

• A better solution is to make the class itself responsible for keeping track of its sole instance. The class ensures that no other instance can be created (by intercepting requests to create new objects) and it provides a way to access the instance.

Page 27: 基于 UML 的面向对象系统分析与设计

Singleton Pattern

Use the Singleton pattern when• 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 28: 基于 UML 的面向对象系统分析与设计

Singleton Class Diagram

Singletoninstance : Singleton

getInstance()if (instance==null) instance=new Singleton();return instance;

Page 29: 基于 UML 的面向对象系统分析与设计

Singleton Particpants

• Singleton– Defines an Instance operation that lets clients

access its unique instance. Instance is a class operation (static method)

– Responsible for creating its own unique instance

• Client– Accesses a Singleton instance solely through the

Singleton’s Instance() method.

Page 30: 基于 UML 的面向对象系统分析与设计

Singleton Consequences

• Controlled access to sole instanceBecause the Singleton class encapsulates its sole

instance, it can have strict control over how and when clients access it.

• Reduced name spaceThe Singleton pattern is an improvement over

global variables. It avoids polluting the name space with global variables that store sole instances.

Page 31: 基于 UML 的面向对象系统分析与设计

Singleton Consequences

• Permits refinement of operations and representationsThe Singleton class may be subclassed and it is easy

to configure an application with an instance of this extended class at run-time.

• More flexible than class operationsAn alternative is to use static member functions.

However it is difficult to change the design to allow more than one instance of a class and static member functions are not polymorphic, so subclasses can not override them.

Page 32: 基于 UML 的面向对象系统分析与设计

Singleton Implementation• Ensuring a unique instance

The Singleton pattern makes the sole instance a normal instance of a class, but that class is written so that only one instance can ever be created. A common way to do this is to hide the operation that creates the instance behind a static class operation that guarantees that only one instance is created.

Page 33: 基于 UML 的面向对象系统分析与设计

Singleton Sample Codeclass Singleton { private static Singleton instance;

static Singleton getInstance() { if (instance == null) // if not created yet instance = new Singleton(); // create once return instance;} // clients access the Singleton exclusively through // the getInstance() member function protected Singleton() {} // the constructor is protected, such that a client // can never instantiate a Singleton }

lazy instantiation

Page 34: 基于 UML 的面向对象系统分析与设计

Singleton Sample Codeclass Singleton { private static Singleton instance;

static Singleton Instance(SingletonType t) { if (instance == null) { if (t==SINGLETON) instance = new Singleton(); if (t==MYSINGLETON) instance = new MySingleton(); } return instance; } protected Singleton() {}}class MySingleton extends Singleton{ … }

Page 35: 基于 UML 的面向对象系统分析与设计

Problems with the above implementation

• protected constructors can be called by subclasses and by other classes in the same package

• two solutions: • make the ClassicSingleton constructor private so that only

ClassicSingleton() methods call it; however, that means

ClassicSingleton cannot be subclassed • put singleton class in an explicit package, so classes in other packages

(including the default package) cannot instantiate singleton instances

Page 36: 基于 UML 的面向对象系统分析与设计

Factory Method Pattern

Page 37: 基于 UML 的面向对象系统分析与设计

Factory Method• Factory Method defines an interface for creating an

object, but let subclasses decide which class to instantiate.

• Factory Method lets a class defer instantiation to subclasses.

Page 38: 基于 UML 的面向对象系统分析与设计

Factory Method

• Frameworks use abstract classes to define and maintain relationships between objects.

• A Framework is often responsible for creating these objects as well.• Consider a framework for applications that can present multiple

documents to the user.• The framework contains abstractions for Application and Document.• Both classes are abstract and clients have to subclass them to realize

their application-specific implementations.• To create a drawing application for example, we define sub-classes

DrawingApplication and DrawingDocument.

Page 39: 基于 UML 的面向对象系统分析与设计

Factory Method• The particular Document sub-class is application specific,

the Application class can not predict the sub-class of a Document to instantiate.

• The Application only knows when a new document should be created, not what kind of Document to create.

• The problem, the framework must instantiate classes, but it only knows about abstract classes, which it cannot instantiate.

• The Factory Method encapsulates the knowledge of which Document sub-class to create and moves this knowledge out of the framework.

Page 40: 基于 UML 的面向对象系统分析与设计

Factory Method Class Diagram

Document

+Open()+Close()+Save()+Revert()

Application

+CreateDocument()+NewDocument()+OpenDocument()

MyDocument MyApplication+CreateDocument()

docs

return new MyDocument();

Document doc = CreateDocument();docs.Add(doc);doc.Open();

Page 41: 基于 UML 的面向对象系统分析与设计

Factory Method Applicability

Use the Factory Method pattern when• A class cannot anticipate the class of objects

it must create.• A class wants its sub-classes to specify the

objects it creates.• Classes delegate responsibility to one of

several helper sub-classes, and you want to localize the knowledge of which helper sub-class is the delegate.

Page 42: 基于 UML 的面向对象系统分析与设计

Factory Method Class Diagram

Product Creator

+FactoryMethod()+Operation()

ConcreteProduct ConcreteCreator

+FactoryMethod()

return new ConcreteProduct();

...product = FactoryMethod();...

Page 43: 基于 UML 的面向对象系统分析与设计

Factory Method Participants

• Product– Defines the interface of objects the factory

method creates

• ConcreteProduct– Implements the Product interface

Page 44: 基于 UML 的面向对象系统分析与设计

Factory Method Participants

• 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 a default ConcreteProduct

– May call the factory method to create a Product object

• ConcreteCreator– Overrides the factory method to return an instance

of a ConcreteProduct

Page 45: 基于 UML 的面向对象系统分析与设计

Factory Method Consequences

• Factory eliminates the need to bind application-specific classes into your code. The code only deals with the Product interface, therefore it can work with any user-defined Concrete-Product classes.

• A potential disadvantage is that clients might have to sub-class the Creator class just to create a particular ConcreteProduct object.

Page 46: 基于 UML 的面向对象系统分析与设计

Factory Method Consequences

• Provides hooks for subclasses: Creating objects inside a class with a factory method is always more flexible than creating an object directly. Factory methods give sub-classes a hook for providing an extended version of an object.

• Connects parallel class hierarchies:

Page 47: 基于 UML 的面向对象系统分析与设计

Factory Method Implementation

• Two main variations of Factory Method– Creator is an abstract class and does not provide

an implementation for factory method. Requires sub-classes to define an implementation, but you do not have to instantiate unforeseeable classes.

– Creator is a concrete class and provides a default implementation for factory method. The Creator uses the factory method primarily for flexibility, allowing sub-classes to change the class of objects their parent class instantiates if necessary.

Page 48: 基于 UML 的面向对象系统分析与设计

Factory Method Implementation

• Parameterized factory methods– The factory method can create multiple kinds of

products. The factory method takes a parameter that identifies the kind of object to create. All objects the factory method creates share the Product interface.

class Creator {Product FactoryMethod(ProductID id) { if (id==MINE) return new MyProduct();

if(id==YOURS) return new YourProduct(); }}

Page 49: 基于 UML 的面向对象系统分析与设计

Factory Method Implementation

• Using templates to avoid subclassing:In C++ one can use a template sub-class of Creator that is

parameterized by the Product class.template <class TheProduct > class Creator{ public: virtual Product* CreateProduct() { return new TheProduct; };};Class MyProduct : public Product { … };Creator<MyProduct> my Creator;

Page 50: 基于 UML 的面向对象系统分析与设计

Abstract Factory Pattern

Page 51: 基于 UML 的面向对象系统分析与设计

Abstract Factory

• Abstract factory provides an interface for creating families of related or dependent objects without specifying their concrete classes.

Page 52: 基于 UML 的面向对象系统分析与设计

Abstract Factory

• Consider a user-interface toolkit that supports multiple look-and-feel standards such as Motif and Presentation Manager.

• Different toolkits define different appearances and behaviors for user interface widgets like scroll-bars, windows and buttons.

• To be portable across different toolkits an application should not hard-code its widgets for a particular toolkit.

Page 53: 基于 UML 的面向对象系统分析与设计

Abstract Factory

• Abstract Factory solves this problem by defining an abstract WidgetFactory class that declares an interface for creating each basic kind of widget.

• There is also an abstract class for each kind of widget, and concrete sub-classes implement widgets for specific toolkits.

• Widget Factory (Factory Method) provides an interface that returns a new widget object for each abstract widget class.

• Clients use Widget Factory to obtain widget instances but are unaware of the concrete classes they are using.

Page 54: 基于 UML 的面向对象系统分析与设计

Abstract Factory

Use the abstract factory pattern when• A system should be independent of how its products are

created, composed and represented.• A system should be configured with 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 55: 基于 UML 的面向对象系统分析与设计

Abstract Factory Class Diagram

AbstractFactory

+CreateProductA()+CreateProductB()

ConcreteFactory1

+CreateProductA()+CreateProductB()

ConcreteFactory2

+CreateProductA()+CreateProductB()

AbstractProductA

ProductA2 ProductA1

AbstractProductB

ProductB2 ProductB1

Client

Page 56: 基于 UML 的面向对象系统分析与设计

Abstract Factory Participants

• AbstractFactory (WidgetFactory)– Declares an interface for operations that

create abstract product objects.

• ConcreteFactory (MotifWidgetFactory, PMWidgetFactory)– Implements the operations to create concrete

products.

Page 57: 基于 UML 的面向对象系统分析与设计

Abstract Factory Participants

• AbstractProduct (Window, ScrollBar)– Declares an interface for a type of product.

• ConcreteProduct (MotifWindow, MotifScrollBar)– Defines a product object to be created by the

corresponding concrete factory.– Implements the AbstractProduct interface

• Client– Uses only the interfaces declared by AbstractFactory and

AbstractProduct

Page 58: 基于 UML 的面向对象系统分析与设计

Abstract Factory Collaborations

• Normally a single instance of a ConcreteFactory class is created at run-time. ConcreteFactory is implemented as a Singleton.

• AbstractFactory defers the creation of product objects to its ConcreteFactory sub-class, using the Factory Method pattern.

Page 59: 基于 UML 的面向对象系统分析与设计

Abstract Factory Consequences

• Abstract Factory isolates classes: It helps you to control the classes of objects that an application creates. It isolates clients from implementation classes as the client manipulates instances solely through their abstract interfaces.

• It makes exchanging product families easy: The class of a concrete factory appears only once in an application – that is where it is instantiated. This makes it easy to change the concrete factory an application uses. It can use different product configurations simply by changing the ConcreteFactory.

Page 60: 基于 UML 的面向对象系统分析与设计

Abstract Factory Consequences

• It promotes consistency among products: When product objects in a family are designed to work together, it is important that the application use objects from only one family at a time.

• Supporting new kinds of products is difficult: Extending abstract factories to produce new kinds of Products is difficult, because the AbstractFactory interface fixes the set of products that can be created. Supporting new products requires extending the factory interface, which involves changing the AbstractFactory class and all its ConcreteFactory sub-classes.

Page 61: 基于 UML 的面向对象系统分析与设计

Abstract Factory Implementation

• Factories as Singletons: An application typically needs only one instance of a ConcreteFactory per product family.

• Creating the Products: AbstractFactory only declares an interface for creating products. It is up to the ConcreteProduct sub-classes to actually create them. The most common way to do this is do define a Factory Method for each Product.– AbstractFactory vs. FactoryMethod– AbstractFactory Creator– ConcreteFactory ConcreteCreator– AbstractProduct Product– Product ConcreteProduct

Page 62: 基于 UML 的面向对象系统分析与设计

Structural Patterns

• Adapter• Composite• Façade• Proxy

Page 63: 基于 UML 的面向对象系统分析与设计

Composite Pattern

Page 64: 基于 UML 的面向对象系统分析与设计

Structural Patterns - Composite

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

Composite: Applicability Represents part-whole hierarchies of objects. Clients ignore the difference between compositions of objects

and individual objects. Clients treat all objects in the composite structure uniformly.

Intent

Page 65: 基于 UML 的面向对象系统分析与设计

Structural Patterns – Composite

Class Diagram

Client

Component

operation()getChild( i:int )

Leaf

operation()

Composite

operation()add( c:Component )remove( c:Component )getChild( i:int )

operation(){

for all g in children g.operation()}

*

Page 66: 基于 UML 的面向对象系统分析与设计

Structural Patterns - Composite

Object Diagram

top : Composite

top : Compositea : Leaf b : Leaf c : Leaf

d : Leaf e : Leaf

Page 67: 基于 UML 的面向对象系统分析与设计

Structural Patterns – Composite

• Declares the interface for objects in the composition.• Implements default behavior for the interface common to all classes, as appropriate.• Declares an interface for accessing and managing its child components.• Optionally defines an interface for accessing a components parent.

Leaf

Represents leaf objects in the composition. Defines behavior for primitive objects in the composition.

Composite

Defines behavior for components having children. Stores child components. Implements child-related operations.

Client

Manipulates objects in the composition through the Component interface.

Component

Participants

Page 68: 基于 UML 的面向对象系统分析与设计

Structural Patterns – Composite

• Clients use the Component class interface to interact with objects in the composite structure.

• If the recipient is a Leaf, then the request is handled directly. • If the recipient is a Composite, then it usually forwards

requests to its child components, possibly performing additional operations before and/or after forwarding.

Collaborations

Page 69: 基于 UML 的面向对象系统分析与设计

Structural Patterns - Façade

Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use.

Applicability Provides a simple interface to a complex subsystem. Decouples the details of a subsystem from clients and other

subsystems. Provides a layered approach to subsystems.

Intent

Page 70: 基于 UML 的面向对象系统分析与设计

Façade Pattern

Page 71: 基于 UML 的面向对象系统分析与设计

Structural Patterns - Façade

Class Diagram

subsystem

Facade

Page 72: 基于 UML 的面向对象系统分析与设计

Structural Patterns - Façade

• Façade– Knows which classes are responsible for each request.

– Delegates client requests to appropriate objects.

• Subsystem classes– Implement subsystem functionality.

– Handle work assigned by the Façade object.

– Have no knowledge of the façade.

Participants

Clients communicate with the subsystem sending requests to the Façade. Reduces the number of classes the client deals with. Simplifies the subsystem.

Clients do not have to access subsystem objects directly.

Collaborations

Page 73: 基于 UML 的面向对象系统分析与设计

Proxy Pattern

Page 74: 基于 UML 的面向对象系统分析与设计

Structural Patterns - Proxy

Provide a surrogate or placeholder for another object to control access to it.

Applicability Remote proxy — provides a local representative for an object in

a different address space. Virtual proxy — creates expensive objects on demand. Protection proxy — controls access to the original object. Smart reference — replacement for a bare pointer

Reference counting Loading persistent object on access Transactional locking

Intent

Page 75: 基于 UML 的面向对象系统分析与设计

Structural Patterns - ProxyClass Diagram

Client

<<abstract>>Subject

request()...

RealSubject

request()...

Proxy

request()...

request(){

... realSubject.request() ...}

Page 76: 基于 UML 的面向对象系统分析与设计

Structural Patterns - ProxyObject Diagram

aClient:

aProxy : Proxy

subject : RealSubject

Page 77: 基于 UML 的面向对象系统分析与设计

Structural Patterns - Proxy• Subject: Defines the common interface for RealSubject and Proxy.• Proxy:

– Maintains reference to real subject– Can be substituted for a real subject– Controls access to real subject– May be responsible for creating and deleting the real subject– Special responsibilities

• Marshaling for remote communication• Caching data• Access validation

RealSubject: Defines the real object that the proxy represents. Client: Accesses the RealSubject through the intervention of the Proxy.

Participants

Proxy forwards requests to RealSubject when appropriate, depending on the kind of proxy.

Collaborations

Page 78: 基于 UML 的面向对象系统分析与设计

Behavioral Patterns

• Command• Observer• State• Visitor

Page 79: 基于 UML 的面向对象系统分析与设计

Command Pattern

Page 80: 基于 UML 的面向对象系统分析与设计

Behavioral Patterns - Command

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

Intent

Parameterize objects by an action In place of “callbacks” Specify, queue, and execute requests at different times Supports undo when Command maintains state information

necessary for reversing command. Added support for logging Command behavior. Support high-level operations built on primitive operations

(transactions).

Applicability

Page 81: 基于 UML 的面向对象系统分析与设计

Behavioral Patterns - Command

Class Diagram

*Client Invoker

action()

Receiver

execute()

<<abstract>>Command

execute()

state

ConcreteCommand

receiver.action()

Page 82: 基于 UML 的面向对象系统分析与设计

Behavioral Patterns - Command

• Command: Declares an interface for executing an operation.• ConcreteCommand

– Defines a binding between a Receiver object and an action.– Implements execute() by invoking a corresponding operation on Receiver.

Client (Application): Creates a Command object and sets its Receiver. Invoker: Asks the Command to carry out a request. Receiver: Knows how to perform the operation associated with a

request. Can be any class.

Participants

Creates a ConcreteCommand object and sets its Receiver. An Invoker stores the ConcreteCommand. Invoker calls execute() on command. ConcreteCommand invokes operation on its receiver.

Collaborations

Page 83: 基于 UML 的面向对象系统分析与设计

Behavioral Patterns - Command

aClient : Client aReceiver:anInvoker :Invoker

aCommand :ConcreteCommand

create( aReceiver )

store( aCommand )

action()

execute()

Sequence Diagram

Page 84: 基于 UML 的面向对象系统分析与设计

Behavioral Patterns - Observer

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

Intent

An abstraction has two aspects, one dependent on the other. When changing one object requires changing others, and you

don’t know how many objects need changed. When an object needs to notify others without knowledge about

who they are.

Applicability

Page 85: 基于 UML 的面向对象系统分析与设计

Observer Pattern

Page 86: 基于 UML 的面向对象系统分析与设计

Behavioral Patterns - Observer Class Diagram

subject

observers

*

update()

ConcreteObserver

attach( observer )detach( observer )notify()

Subject

for all o in observers o.update()

getState()

subjectState

ConcreteSubject

update()

<<interface>>Observer

observerState := subject.getState()

Page 87: 基于 UML 的面向对象系统分析与设计

Behavioral Patterns - Observer

• Subject– Knows its observers, but not their “real” identity.– Provides an interface for attaching/detaching observers.

• Observer– Defines an updating interface for objects that should be identified of changes.

ConcreteSubject Stores state of interest to ConcreteObserver objects. Sends update notice to observers upon state change.

ConcreteObserver Maintains reference to ConcreteSubject (sometimes). Maintains state that must be consistent with ConcreteSubject. Implements the Observer interface.

Participants

ConcreteSubject notifies observers when changes occur. ConcreteObserver may query subject regarding state change.

Collaborations

Page 88: 基于 UML 的面向对象系统分析与设计

Behavioral Patterns - Observer

Sequence Diagram

subject :ConcreteSubject

observer1 :ConcreteObserver

observer2 :ConcreteObserver

attach( observer1 )

attach( observer2 )

update()

getState()

update()

getState()

notify()

Page 89: 基于 UML 的面向对象系统分析与设计

Behavioral Patterns - State

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

Intent

An object’s behavior depends on its state, and it must change its behavior at run-time depending on its state.

Operations have large, multipart conditional statements that depend on the object’s state. Usually represented by constants. Some times, the same conditional structure is repeated.

Applicability

Page 90: 基于 UML 的面向对象系统分析与设计

State Pattern

Page 91: 基于 UML 的面向对象系统分析与设计

Behavioral Patterns - State

Class Diagram

staterequest()

Context

state.handle();

handle()

<<abstract>>State

handle()

ConcreteStateA

handle()

ConcreteStateB

Page 92: 基于 UML 的面向对象系统分析与设计

Behavioral Patterns - State

• Context– Defines interface of interest to clients.– Maintains an association with a subclass of State, that defines the current state.

• State– Defines an interface for encapsulating the behavior with respect to state.

• ConcreteStatex– Each subclass implements a behavior associated with a particular state of the Context.

Participants

Context delegates state-specific behavior to the current concrete State object. The state object may need access to Context information; so the context is

usually passed as a parameter. Clients do not deal with State object directly. Either Context or a concrete State subclass can decide which state succeeds

another.

Collaborations

Page 93: 基于 UML 的面向对象系统分析与设计

Visitor Pattern

Page 94: 基于 UML 的面向对象系统分析与设计

Behavioral Patterns - Visitor

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

Intent

An object structure contains many disparate classes, and operations need to be performed based on concrete classes.

Many distinct operations need to be performed on an object structure.

An object structure rarely changes, but new operations need to be defined over the structure.

Applicability

Page 95: 基于 UML 的面向对象系统分析与设计

Behavioral Patterns - Visitor

Class Diagram

*Client

visitA( element : ConcreteElementA )visitB( element : ConcreteElementB )

<<abstract>>Visitor

visitA( element : ConcreteElementA )visitB( element : ConcreteElementB )

ConcreteVisitor1

visitA( element : ConcreteElementA )visitB( element : ConcreteElementB )

ConcreteVisitor2

ObjectStructureaccept( v : Visitor )

<<abstract>>Element

accept( v : Visitor )operationA()

ConcreteElementA

accept( v : Visitor )operationB()

ConcreteElementB

v.visitA( this ) v.visitB( this )

Page 96: 基于 UML 的面向对象系统分析与设计

Behavioral Patterns - Visitor

• Visitor — declares a visit operation for each class within the object structure aggregation.

• ConcreteVisitor — implements each operation declared by Visitor. Provides algorithm context.

• Element — defines an accept operation taking a Visitor as an argument.

ConcreteElementX — implements an accept operation taking a Visitor as an argument.

ObjectStructure Enumerates its elements; potentially disparate classes. May provide a high level interface for visitor to visit its elements. Potentially a composite or just a general collection.

Participants

A client creates an instance of a concrete Visitor subclass. Client requests the ObjectStructure to allow the visitor to visit each. When visited, Element invokes the appropriate operation on Visitor;

overloading to know the element type.

Collaborations

Page 97: 基于 UML 的面向对象系统分析与设计

Behavioral Patterns - Visitor

Sequence Diagram

aStruct :ObjectStructure

v : VisitorelemB :ConcreteElementB

elemA :ConcreteElementA

accept( v )

accept( v ) visitConcreteElementB( elemB )

operationB()

visitConcreteElementA( elemA )

operationA()

Page 98: 基于 UML 的面向对象系统分析与设计

How to Select & Use Design Patterns

• Scan Intent Sections• Study How Patterns Interrelate• Study Patterns of Like Purpose• Examine a Cause of Redesign• Consider What Should Be Variable in Your Design

Read the pattern once through for an overview: appears trivial, but not Go back and study the structure, participants, and collaborations

sections Look at Sample Code: concrete example of pattern in code Choose names for pattern participants Define the classes Define application specific names for operations in the pattern Implement the operations to carry out the responsibilities and

collaborations in the pattern

How to Use

How to Select (> 20 in the book, and still growing … fast?, more on Internet)

Page 99: 基于 UML 的面向对象系统分析与设计

Mediator Pattern

Page 100: 基于 UML 的面向对象系统分析与设计

Mediator Pattern

• Different dialog boxes will have different dependencies between widgets, which makes it impossible to simply reuse a standard set of widget classes.

• Instead widget classes have to be customized to reflect dialog-specific dependencies, which would require a large number of separate subclasses for different types of dialogs.

Page 101: 基于 UML 的面向对象系统分析与设计

Coupling between Classes

SpecialButton

SpecialEntry Field

SpecialListBox

list button field

field

button

list

Page 102: 基于 UML 的面向对象系统分析与设计

Mediator Pattern

• Encapsulating the collective behavior in a separate Mediator object avoids these problems.

• A Mediator object is responsible for controlling and coordinating the interactions of a group of objects.

• The Mediator serves as an intermediary that keeps objects in the group from refering to each other explicitly.

• The objects only know the Mediator thereby reducing the number of interactions.

Page 103: 基于 UML 的面向对象系统分析与设计

Mediator Pattern

FormDialogDirector

Clientdirector

Button EntryField

ListBox

director director

director

button field

list

Page 104: 基于 UML 的面向对象系统分析与设计

Mediator Pattern

• The FormDialogDirector is the mediator between the widgets in the dialog box.

• The FormDialogDirector knows the widgets in a dialog and coordinates their interaction.

• The FormDialogDirector acts as a hub of communications for widgets.

Page 105: 基于 UML 的面向对象系统分析与设计

Mediator Sequence Diagram

aListBox

WidgetChanged()

SetText()

anEntryField

ShowDialog()

aClientaFormDialogDirector

GetSelection()

aButton

EnableButton()

Page 106: 基于 UML 的面向对象系统分析与设计

Mediator Structure

DialogDirector ShowDialog()

CreateWidgets()WidgetChanged(w)

Widget Changed()

director

FormDialogDirector CreateWidgets()

WidgetChanged(w)

ListBox GetSelection()

field

EntryField SetText()

list

Director->WidgetChanged(this)

Page 107: 基于 UML 的面向对象系统分析与设计

Mediator Pattern

• DialogDirector is an abstract class that defines the overall behavior of a dialog.

• Clients call the ShowDialog operation to display the dialog on the screen.

• CreateWidgets is an abstract operation for creating the widgets of a dialog.

• WidgetChanged is another abstract operation, widgets call it to inform their director that they have changed.

• DialogDirector subclasses override CreateWidgets to create the proper widgets, and they override WidgetChanged to handle the changes.

Page 108: 基于 UML 的面向对象系统分析与设计

Mediator Sample Code

class DialogDirector

{

public:

virtual void ShowDialog();

virtual void WidgetChanged(Widget *)=0;

protected:

DialogDirector();

virtual void CreateWidgets() = 0;

};

Page 109: 基于 UML 的面向对象系统分析与设计

Mediator Sample Codeclass Widget{public:

Widget(DialogDirector*); virtual void Changed(); virtual void HandleMouseEvent(MouseEvent& event);private: DialogDirector* director_;};

void Widget::Changed() { director->WidgetChanged(this); }

Page 110: 基于 UML 的面向对象系统分析与设计

Mediator Sample Code

class ListBox : public Widget

{

public:

ListBox(DialogDirector*);

virtual const string GetSelection();

virtual void HighLight(string selection);

virtual void SetList(list<string> newlistItems);

virtual void HandleMouseEvent(MouseEvent& event);

private:

list<string> listItems;

};

Page 111: 基于 UML 的面向对象系统分析与设计

Mediator Sample Code

class EntryField : public Widget{public: EntryField(DialogDirector*); virtual const string GetText(); virtual void SetText(const string newtext); virtual void HandleMouseEvent(MouseEvent& event);private: string text;};

Page 112: 基于 UML 的面向对象系统分析与设计

Mediator Sample Code

class Button : public Widget

{

public:

Button(DialogDirector*);

virtual void SetText(const string newtext);

virtual void HandleMouseEvent(MouseEvent& event);

virtual void Activate();

virtual void DeActivate();

private:

bool active;

};

Page 113: 基于 UML 的面向对象系统分析与设计

Mediator Sample Code

class FormDialogDirector : public DialogDirector{public: FormDialogDirector() virtual void WidgetChanged(Widget *);protected: virtual void CreateWidgets();private:

ListBox* list; EntryField* field; Button* ok_button; Button* cancel_button;};

Page 114: 基于 UML 的面向对象系统分析与设计

Mediator Sample Code

void FormDialogDirector::CreateWidgets(){ list = new ListBox(this); field = new EntryField(this); ok_button = new Button(this); cancel_button = new Button(this); ok_button->DeActivate(); ok_button->SetText(”OK”); cancel_button->Activate(); cancel_button->SetText(”Cancel”); // fill the ListBox with the available names list->SetList(...);}

Page 115: 基于 UML 的面向对象系统分析与设计

Mediator Sample Code

void FormDialogDirector::WidgetChanged (Widget* ChangedWidget) { if (ChangedWidget==list)

field->SetText(list->GetSelection()); if (ChangedWidget==field) { list->Highlight(field->GetText()); if (field->GetText() != ””) ok_button->Activate(); else ok_button->DeActivate(); } } if (ChangedWidget==ok_button)

...}

Page 116: 基于 UML 的面向对象系统分析与设计

Mediator Applicability

Use the Mediator pattern when• A set of objects communicate in well-defined complex ways.

The resulting interdependencies are unstructured and difficult to understand.

• Reusing an object is difficult because it refers to and communicates with many other objects.

• A behavior that is distributed between several classes should be customizable without a lot of subclassing.

Page 117: 基于 UML 的面向对象系统分析与设计

Mediator Pattern Structure

Mediator Colleague mediator

ConcreteMediator

ConcreteColleagueA

ConcreteColleagueB

Page 118: 基于 UML 的面向对象系统分析与设计

Mediator Pattern Participants

• Mediator – defines an interface for communicating with

Colleague objects.• ConcreteMediator

– Implements cooperative behavior by coordinating Colleague objects.

• Colleague classes– Each colleague knows its mediator– Each colleague communicates with its Mediator

whenever it would have otherwise communicated with another colleague

Page 119: 基于 UML 的面向对象系统分析与设计

Mediator Pattern Collaborations

• Colleagues send and receive requests from a Mediator object.

• The Mediator implements the cooperative behavior by routing requests between the appropriate colleagues

Page 120: 基于 UML 的面向对象系统分析与设计

Mediator Pattern Consequences

• The Mediator pattern limits subclassing. A mediator localizes behavior that otherwise would be distributed among several objects. Changing this behavior requires subclassing Mediator only, Colleague classes can be reused.

• The Mediator pattern decouples colleagues. A mediator promotes loose coupling between colleagues. You can vary and reuse Colleague and Mediator classes independently.

Page 121: 基于 UML 的面向对象系统分析与设计

Mediator Pattern Consequences

• The Mediator pattern simplifies object protocols. A mediator replaces many-to-many interactions with one-to-many interactions between the mediator and its colleagues. One-to-many relationships are easier to understand, maintain and extend.

• The Mediator pattern abstracts how objects cooperate. Making mediation an independent concept and encapsulating it in an object lets you focus on how objects interact apart from their individual behavior. That can help clarify how objects interact in a system.

Page 122: 基于 UML 的面向对象系统分析与设计

Mediator Pattern Consequences

• The mediator pattern centralizes control. The Mediator pattern trades complexity of interaction for complexity in the mediator. Because a mediator encapsulates protocols, it can become more complex than an individual colleague. This can make the mediator itself a monolith that is hard to maintain.

Page 123: 基于 UML 的面向对象系统分析与设计

Mediator Pattern Implement.

• Omitting the abstract Mediator class. There is no need to define an abstract

Mediator class when colleagues work with only one mediator. The abstract coupling that the Mediator class provides lets colleagues work with different subclasses and vice versa.

Page 124: 基于 UML 的面向对象系统分析与设计

Mediator Pattern Implement.

• Colleague-Mediator communication. Colleagues have to communicate with their mediator when an event of interest occurs. One approach is to implement the Mediator as an Observer. Colleague classes act as Subjects, sending notifications to the mediator whenever they change state. The mediator responds by propagating the effects of the change to the other colleagues.

Page 125: 基于 UML 的面向对象系统分析与设计

Mediator Pattern Game

GameManager

Playermanager

Token Board

Dice

manager manager

manager

token board

dice

Page 126: 基于 UML 的面向对象系统分析与设计

Chain of Responsibility (CoR) Pattern

Page 127: 基于 UML 的面向对象系统分析与设计

Behavioral Patterns – Chain of Responsibility (CoR)

Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

Intent

You want to decouple a request's sender and receiver Multiple objects, determined at runtime, are candidates to handle a

request You don't want to specify handlers explicitly in your code

Applicability

Page 128: 基于 UML 的面向对象系统分析与设计

Behavioral Patterns - Command

Class Diagram

ConcreteHandler1

handleRequest()

ConcreteHandler2

handleRequest()

ClientHandler

handleRequest()

successor

Page 129: 基于 UML 的面向对象系统分析与设计

Behavioral Patterns - Command

• Handler:– Defines the interface for handling the requests– May implement the successor link

• ConcreteHandler– Handles requests it is responsible for– Can access its successor– Handles the request if it can do so, otherwise it forwards the request to

its successor Client: initiates the request to a ConcreteHandler object on the chain.

Participants

If you use the CoR pattern, remember: Only one object in the chain handles a request Some requests might not get handled

Those restrictions, of course, are for a classic CoR implementation. In practice, those rules are bent; for example, servlet filters are a CoR implementation that allows multiple filters to process an HTTP request.

Page 130: 基于 UML 的面向对象系统分析与设计

Behavioral Patterns - Command

aClient : Client aReceiver:anInvoker :Invoker

aCommand :ConcreteCommand

create( aReceiver )

store( aCommand )

action()

execute()

Sequence Diagram

Page 131: 基于 UML 的面向对象系统分析与设计

Expanding Our Horizons

Page 132: 基于 UML 的面向对象系统分析与设计

OO Design

• Fundamental Concepts– Objects

• Traditional way: bundle of data and method• New way: things with responsibility

– Encapsulation• Traditional way: hiding data• New way: the ability to hiding anything

– Abstract classes/inheritance• Traditional way: for specialization and reuse• New way: as method of classifying objects

• Find what is varying and Encapsulate it