Slide 1: 软件设计模式 ( 二 )
潘爱民 http://www.icst.pku.edu.cn/CompCourse
Slide 2: 内容
• 复习 • 续:介绍一些重要的模式
– Structural Patterns – Behavioral Patterns
Slide 3: 复习: pattern 定义
• 定义:
– 特定环境中问题的成功解决方案中的静态、动态结构 ,以及结构元素相互之间的协作关系 – Design patterns represent solutions to problems that arise when developing software within a particular context
• 关于 pattern 的研究状况
– 研究历史 – 现状
• pattern 与框架 • pattern 的分类
– 粒度
Slide 4: 复习:如何描述一个模式
• 关键要素
– – – – – Design pattern name , Aliases or Also Known As Problem , Intent or Goal Forces , Constraints , Motivation Context , Applicability Solution
• • • • Structure Participants Collaboration Implementation
– Evaluation , Resulting Context , Consequences – Related Patterns – Examples , Known uses
Slide 5: 复习: creational patters
• Factory Method
– 本质:用一个 virtual method 完成创建过程
• Abstract Factory
– 一个 product 族的 factory method 构成了一个 factory 接口
• Prototype
– 通过 product 原型来构造 product , Clone+prototype manager
• Builder
– 通过一个构造算法和 builder 接口把构造过程与客户隔离开
• Singleton
– 单实例类型,如何构造这单个实例?如何访问这单个实例 ?
• Finder
– 把对象的获取过程与客户隔离开
Slide 6: creational patterns 小结
• 了解每一种模式的实质
– 具体实现的时候可能会有变化情况,或者扩展,或者 退化
• factory method 是基础, abstract factory 是它的扩 展 • factory method 、 abstract factory 、 prototype 都涉 及到类层次结构中对象的创建过程,有所取舍
– – – – prototype 需要 prototype manager factory method 需要依附一个 creator 类 abstract factory 需要一个平行的类层次 根据应用的其他需求,以及语言提供的便利来决定使 用哪种模式
Slide 7: creational patterns 小结 ( 续 )
• builder 往往适合于特定的结构需要,它所针对 的 product 比较复杂 • singleton 有比较强烈的物理意义,可以用在许 多细微的地方,不一定与类层次关联 • finder 模式需要有一定范围内的对象管理功能 • 这些 patterns 都很常见,有时需要结合两种或 者多种模式完成系统中对象的构造过程
Slide 8: Structural Patterns
• • • • • • • Adapter Bridge Composite * Decorator Facade Flyweight * Proxy
Slide 9: 模式 7 : Adapter ( 一 )
• Aliases : Wrapper • 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.
Slide 10: Adapter 模式 ( 二 )
• Applicability : Use the Adapter pattern 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.
Slide 11: • Struct
class adapter
Adapter 模式 ( 三 )
object adapter
Slide 12: Adapter 模式 ( 三 )
• Participants
– Client 、 Target 、 Adaptee 、 Adapter
• Collaborations
– class adapter —— delegation – object adapter —— container
Slide 13: Adapter 模式 ( 四 )
• Evaluation
– 本质上是两种重用模型 – class adapter :
• 无法 adapt adaptee 的子类,但是可以重载 adaptee 的行为
– object adapter
• 可以 adapt adaptee 的所有子类
– How much adapting does Adapter do? – Pluggable adapters – Using two-way adapters to provide transparency
• 针对 class adapter ,用多重继承来实现
Slide 14: Adapter 模式 ( 五 )
• Implementation
– 使用 C++ 继承机制实现 class adapter – 使用内嵌对象技术实现 object adapter – Pluggable adapters ,三种实现方案
• 使用抽象方法定义 • 使用代理对象 • 参数化技术
这三种方法的实质:如何在一个类中定义抽象 操作,供客户插入?—— hook 技术
Slide 15: Adapter 模式 ( 六 )
• Related Patterns
– Bridge – Decorator – Proxy
• Examples
– DrawCli : COleDrawObj – C++ STL – COM 中的 site
Slide 16: 模式 8 : Bridge( 一 )
• Aliases : Handle/Body • Intent
– Decouple an abstraction from its implementation so that the two can vary independently
• Motivation
– 要做到“抽象 ( 接口 ) 与实现分离”,最常用的办 法是定义一个抽象类,然后在子类中提供实现。也 就是说,用继承机制达到“抽象 ( 接口 ) 与实现分 离” – 但是这种方法不够灵活,继承机制把实现与抽象部 分永久地绑定起来,要想独立地修改、扩展、重用 抽象 ( 接口 ) 与实现都非常困难。
Slide 17: Bridge 模式 ( 二 )
• Applicability : Use the Bridge pattern when
– – – – – 编译时刻无法确定抽象 ( 接口 ) 与实现之间的关系 抽象部分与实现部分都可以通过子类化而扩展 对一个实现的修改不影响客户 ( 无须重新编译 ) 在 C++ 中,对客户完全隐瞒实现细节 因为扩展的原因,需要把一个类分成两部分, ( 以 便灵活组合 ) – 在多个对象之间共享数据,但客户不需要知道
Slide 18: Bridge 模式 ( 三 )
• Struct
• Participants
– Client, Abstraction, RefinedAbstraction, Implementor, ConcreteImplementor
• Collaborations
Slide 19: Bridge 模式 ( 四 )
• Evaluation
– 抽象部分与实现部分的分离,可以在运行时刻 连接起来 二进制兼容性 – 提高可扩充性:抽象与实现两部分可以单独扩 充 – 对客户隐藏实现细节
Slide 20: Bridge 模式 ( 五 )
• Implementation
– Only one Implementor – Creating the right Implementor object 如何创建?根据客户环境,或者通过 factory – Sharing implementors
• 资源管理:引用计数技术
– Using multiple inheritance
Slide 21: Bridge 模式 ( 六 )
• Related Patterns
– Abstract Factory 可以用来创建和配置 Bridge 模式 – 与 Adapter 模式的区别
• Examples
– handle :文件 handle 、窗口 handle
Slide 22: 插: Handle/Body
Counted Handle/Body
class StringRep { friend class String; StringRep(const char *s); ~StringRep(); int count; char *rep; }; class String { public: String(); String(const String &s); String &operator=(const String &s); ~String(); String(const char *s); .... private: StringRep *rep; };
Slide 23: 模式 9 : Composite( 一 )
• Intent
– Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
• Motivation
– 一些部件对象经过组合构成的复合部件对象仍然具有单个部件对 象的接口,这样的复合部件对象被称为“容器 (container)” – 复合部件与单个部件具有同样的接口,所有接口包含两部分:单 个部件的功能、管理子部件的功能 – 递归组合
Slide 24: Composite 模式 ( 二 )
• Applicability : Use the Composite pattern when – you want to represent part-whole hierarchies of objects. – you want clients to be able to ignore the difference between compositions of objects and individual objects. Clients will treat all objects in the composite structure uniformly.
Slide 25: Composite 模式 ( 三 )
• Struct
• Participants
– Client, Component, Leaf, Composite
• Collaborations
Slide 26: 典型的 composite 对象结构
Slide 27: Composite 模式 ( 四 )
• Evaluation
– defines class hierarchies consisting of primitive objects and composite objects 。定义了包含 leaf
对象和 composite 对象的类层次接口。——递归结 构
– makes the client simple 。客户一致地处理复合对
象和单个对象
– makes it easier to add new kinds of components 。易于增加新类型的组件
– can make your design overly general 。使得系统过于 一般化,无法限制类型的组合,可以在运行时刻通 过类型检查加以弥补
Slide 28: Composite 模式 ( 五 )
• Implementation
– – – – – – – – – Explicit parent references Sharing components Maximizing the Component interface Declaring the child management operations Should Component implement a list of Components? Child ordering Caching to improve performance Who should delete components? What's the best data structure for storing components?
Slide 29: Composite 模式 ( 六 )
• Related Patterns
– Decorator 、 Flyweight 、 Iterator 、 Visitor
• Examples
– 广泛应用于 OO 领域 – MFC 中的 CWnd – 组件层次: ActiveX Container
Slide 30: 模式 10 : Facade( 一 )
• Intent – Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. • Motivation
– 使系统的各子系统之间的关联最小,引入一个 facade 对象,为子 系统提供一个简单的、泛化的设施
Slide 31: Facade 模式 ( 二 )
• Applicability : Use the Facade pattern when
– 为一个复杂的子系统提供一个简单接口时。 子系统往往会非常复杂,但是其接口应该尽可 能地简单,特别是对于一般用户而言 – 客户与抽象类的实现部分之间必然存在一定的 依赖性, facade 可以降低这种依赖性 – 在多个子系统的结构中,使用 facade 模式定义 子系统的入口点,有助于降低各子系统之间的 依赖性
Slide 32: Facade 模式 ( 三 )
• Struct
• Participants
– facade, subsystem classes
• Collaborations
Slide 33: Facade 模式 ( 四 )
• Evaluation
– 简化子系统的接口,方便客户使用子系统 – 化“紧耦合”为“松耦合” —— 实现组件软件的关键技术 – facade 模式并不限制客户直接访问子系统的 内部类和对象
• Implementation
– 以抽象类的形式定义 facade ,进一步 decouple ,从 而完全隔离子系统的细节
– Public versus private subsystem classes
Slide 34: Facade 模式 ( 五 )
• Related Patterns
– facade 对象的创建: singleton 、 abstract factory
• Examples MDI Framework Map Module
CDrawView CDrawDoc
Netscape Browser
Map Plugin Module
Map Module
CDrawView CDrawDoc
MFC library
Fake MFC library
Slide 35: 模式 11 : FlyWeight( 一 )
• Intent
– Use sharing to support large numbers of fine-grained objects efficiently.
• Motivation
– 当对象的粒度太小的时候,大量对象将会产生巨大的 资源消耗,因此考虑用共享对象 (flyweight) 来实现逻 辑上的大量对象。 Flyweight 对象可用于不同的 context 中,本身固有的状态不随 context 发生变化, 而其他的状态随 context 而变化
Slide 36: FlyWeight 模式 ( 二 )
• Applicability : Use the FlyWeight pattern when all of the following are true:
– 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. Since flyweight objects may be shared, identity tests will return true for conceptually distinct objects.
Slide 37: FlyWeight 模式 ( 三 )
• Struct
Slide 38: FlyWeight 模式 ( 四 )
• Struct( 续 )
• Participants
– client, flyweight, concreteFlyweight, FlyweightFactory, – UnsharedConcreteFlyweight
• Collaborations
Slide 39: FlyWeight 模式 ( 五 )
• Evaluation
– 把对象的状态分开: intrinsic and extrinsic – 节约存储空间:内部状态的共享节约了大量空间, 外部状态可通过计算获得从而进一步节约空间 – flyweight 与 composite 结合。 Flyweight 为 leaf 节点 ,并且父节点只能作为外部状态
• Implementation
– Removing extrinsic state ,尽可能做到实时计算 ( 通 过一个小的数据结构 ) – Managing shared objects ,客户不能直接实例化 flyweight ,必须通过管理器,例如 FlyweightFactory 。 flyweight 的生命周期管理,引用计数和回收
Slide 40: FlyWeight 模式 ( 六 )
• Related Patterns
– 与 Composite 模式组合 – 可以用 flyweight 实现 State 和 Strategy 模式中的对象
• Examples
– Excel 中 cell 的管理
• IOleItemContainer 接口允许客户发现每一个 cell 对象 • 用 flyweight 实现 cell 对象 —— tearoff 技术 • 对状态的有效管理是对象技术的一个进步
– “Design Patterns” 中提到的文档编辑器的例子
Slide 41: Structural Patterns : Decorator
Slide 42: Structural Patterns : Proxy
Slide 43: Structural patterns 小结
• Adapter 、 bridge 、 facade
– adapter 用于两个不兼容接口之间的转接 – bridge 用于将一个抽象与多个可能的实现连接起来 – facade 用于为复杂的子系统定义一个新的简单易用 的接口
• composite 、 decorator 和 proxy
– composite 用于构造对象组合结构 – decorator 用于为对象增加新的职责 – proxy 为目标对象提供一个替代者
• flyweight
– 针对细粒度对象的一种全局控制手段
Slide 44: Behavioral Patterns
• • • • • • • • • • • Chain of Responsibility * Command Interpreter * Iterator Mediator * Memento * Observer State * Strategy Template Method * Visitor
Slide 45: 模式 12 : Command( 一 )
• Aliases
– Action, Transaction – functor (function object)
• Intent
– Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
• Motivation
– 把请求信息和请求执行过程封装起来 – framework 往往需要把命令请求与处理请求的对象分 开, command 模式可以把调用操作的对象与操作的目 标对象分开 – 允许通过多种途径调用同一个请求。——请求的重用
Slide 46: Command 模式 ( 二 )
• Applicability : Use the Command pattern when :
– – – – 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 —— transactions
Slide 47: Command 模式 ( 三 )
• Struct
• Participants
– Client, Command 、 ConcreteCommand 、 Invoker 、 Receiver
Slide 48: Command 模式 ( 四 )
• Collaborations
Slide 49: Command 模式 ( 五 )
• Evaluation
– Command decouples the object that invokes the operation from the one that knows how to perform it. – Commands are first-class objects. They can be manipulated and extended like any other object. – You can assemble commands into a composite command. An example is MacroCommand. – It's easy to add new Commands, because you don't have to change existing classes.
• Implementation
– – – – How intelligent should a command be? Supporting undo and redo Avoiding error accumulation in the undo process Using C++ templates
Slide 50: Command 模式 ( 六 )
• Related Patterns
– Composite 模式可用来实现 command 组合 – 为实现 undo/redo ,可以用其他行为模式来管理状态,如 memento 模式。 Command 被放到 history list 之前,可以用 prototype 模式复制自身
• Examples
Slide 51: 模式 13 : Iterator( 一 )
• Aliases : Cursor • Intent
– Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
• Motivation
– An aggregate object such as a list should give you a way to access its elements without exposing its internal structure. – Separating the traversal mechanism from the List object lets us define iterators for different traversal policies without enumerating them in the List interface.
Slide 52: Iterator 模式 ( 二 )
• Applicability : Use the Iterator pattern when : – 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 (that is, to support polymorphic iteration).
Slide 53: Iterator 模式 ( 三 )
• Struct
• Participants
– Iterator 、 ConcreteIterator 、 Aggregate 、 ConcreteAggrega te
• Collaborations
Slide 54: Iterator 模式 ( 四 )
• Evaluation
– It supports variations in the traversal of an aggregate – Iterators simplify the Aggregate interface – More than one traversal can be pending on an aggregate
• Implementation
– 实现可以非常灵活 – Who controls the iteration?
• external iterator versus internal iterator
– Who defines the traversal algorithm?
• Aggregate 本身定义算法 —— Cursor mode • iterator 定义算法 —— iterator 如何访问数据
– How robust is the iterator?
Slide 55: Iterator 模式 ( 五 )
• Implementation( 续 )
– Additional Iterator operations.
• 基本操作: First, Next, IsDone, and CurrentItem
– Using polymorphic iterators —— iterator 资源释放 – Iterators may have privileged access – Iterators for composites —— 适合于 internal iterator 或者 cursor 方式的 iterator – Null iterators
Slide 56: Iterator 模式 ( 六 )
• Related Patterns
– Composite : iterator 常被用于 composite 模式的复合结 构 – Polymorphic iterators rely on factory methods to instantiate the appropriate Iterator subclass.
• Examples
– COM enumerator : connectable object 、… – ADO/OLE DB – C++ STL
• 在 STL 中, iterator 是连接 algorithm 和 container 的桥梁
Slide 57: 模式 14 : Observer( 一 )
• Aliases : Dependents, Publish-Subscribe • Intent
– Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
• Motivation
– 把系统分成一些相互关联的类或者对象,如何维护这 些类的实例一致性? – The key objects in this pattern are subject and observer
• One-to-many relationship • A subject may have any number of dependent observers. • All observers are notified whenever the subject undergoes a change in state.
Slide 58: Observer 模式 ( 二 )
• Applicability : Use the Observer pattern when :
– When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently. – When a change to one object requires changing others, and you don't know how many objects need to be changed. – When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don't want these objects tightly coupled.
Slide 59: Observer 模式 ( 三 )
• Struct
• Participants
– Subject 、 ConcreteSubject 、 Observer 、 ConcreteObserver
Slide 60: Observer 模式 ( 四 )
• Collaborations
Slide 61: Observer 模式 ( 五 )
• Evaluation
– Abstract coupling between Subject and Observer – Support for broadcast communication – Unexpected updates
• Implementation
– – – – – – Mapping subjects to their observers. Observing more than one subject Who triggers the update? Client or subject ? Making sure Subject state is self-consistent before notification subject 向 observer 传递变化信息 中间插入 ChangeManager
Slide 62: Observer 模式 ( 六 )
• Related Patterns
– Mediator :用 Mediator 模式封装复杂的更新语义
• Examples
– COM property page – COM+ Event Model , – MVC
Slide 63: 模式 15 : Strategy( 一 )
• Aliases : Policy • Intent
– Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
• Motivation
– 有些算法对于某些类是必不可少的,但是不适合于硬 编进类中。客户可能需要算法的多种不同实现,允许 增加新的算法实现或者改变现有的算法实现 – 我们可以把这样的算法封装到单独的类中,称为 strategy
Slide 64: Strategy 模式 ( 二 )
• Applicability : Use the Strategy pattern when : – 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 operations.
Slide 65: Strategy 模式 ( 三 )
• Struct
• Participants
– Strategy 、 ConcreteStrategy 、 Context
• Collaborations
– Strategy and Context interact to implement the chosen algorithm – A context forwards requests from its clients to its strategy
Slide 66: Strategy 模式 ( 四 )
• Evaluation – Families of related algorithms – An alternative to subclassing – Strategies eliminate conditional statements – Clients must be aware of different Strategies – Communication overhead between Strategy and Context – Increased number of objects • Implementation – Defining the Strategy and Context interfaces – Strategies as template parameters – Making Strategy objects optional
Slide 67: Strategy 模式 ( 五 )
• Related Patterns
– flyweight :考虑用 flyweight 模式来实现 strategy 对象
• Examples
– ATL 中 COM 对象的线程模型支持
Slide 68: 模式 16 : 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.
• Motivation
– 为了把一个操作作用于一个对象结构中,一种做法是 把这个操作分散到每一个节点上。导致系统难以理解 、维护和修改 – 把这样的操作包装到一个独立的对象 (visitor) 中。然 后在遍历过程中把此对象传递给被访问的元素。
Slide 69: 不用 visitor 的 compiler 例子
Operation Class VariableRefNode AssignmentNode ... TypeCheck GenerateCode PrettyPrint
Slide 70: 使用 visitor 的 compiler 例子
Class class operation VariableRefNode VisitVariableRef VisitVariableRef VisitVariableRef AssignmentNode VisitAssignment VisitAssignment VisitAssignment TypeCheckVisitor GenerateCodeVisitor PrettyPrintVisitor
Slide 71: Visitor 模式 ( 二 )
• Applicability : Use the Visitor pattern when
– 一个对象结构包含许多对象类,我们想执行一 些依赖于具体类的操作 – 要对一个对象结构中的对象进行很多不同的并 且不相关的操作,又不想改变这些对象类 – 定义对象结构的类很少改变,但是经常要在此 结构上定义新的操作。改变对象结构类,需要 重定义所有 visitor 的接口
Slide 72: Visitor 模式 ( 三 )
• Struct
Slide 73: Visitor 模式 ( 四 )
• Participants
– Client 、 Visitor 、 ConcreteVisitor 、 ObjectStructure 、 Ele ment 、 ConcreteElement
• Collaborations
– client 先创建一个 ConcreteVisitor ,然后遍历 ObjectStructure
Slide 74: Visitor 模式 ( 五 )
• Evaluation
– – – – – – Visitor makes adding new operations easy A visitor gathers related operations and separates unrelated ones Adding new ConcreteElement classes is hard. 即使不是类层次, visitor 也可以实施 状态累积 visitor 要访问每个元素的状态,所以要打破封装
• Implementation – double-dispatch , Accept 实现了 double dispatch This is the key to the Visitor pattern: The operation that gets executed depends on both the type of Visitor and the type of Element it visits. – Who is responsible for traversing the object structure?
Slide 75: Visitor 模式 ( 六 )
• Related Patterns – Composite : visitor 常常被用于 composite 模式组成的
结构中
• Examples
– 编译器实现
Slide 76: 其他 Behavioral Patterns
• Chain of Responsibility
– 请求的处理过程,沿着链传递, decouple 发送和接收方
• Interpreter
– 在类层次结构中,在特定环境的“ interpret” 过程
• Mediator
– 用一个 mediator 来 decouple 各同等单元
• Memento
– 在对象之外保存对象的内部状态
• State
– 把一个对象的状态独立出来,动态可变换状态对象的类型
• Template Method
– 在基类中定义算法的骨架,把某些细节延迟到子类中
Slide 77: Behavioral Patterns 小结
• Strategy 、 Iterator 、 Mediator 、 State 、 comm and
– 用一个对象来封装某些特性,比如变化、交互、状 态、行为、命令
• Mediator 、 Observer
– Observer 建立起 subject 和 observer 之间的松耦合连 接 – mediator 把约束限制集中起来, - 〉中心控制
• command 、 Chain of Responsibility 、 interpreter
– command 模式侧重于命令的总体管理 – Chain of Responsibility 侧重于命令被正确处理