设计模式之桥梁(Bridge)模式
2012-03-01 12:14
411 查看
一、 桥梁(Bridge)模式
桥梁模式是一个非常有用的模式,也是比较复杂的一个模式。熟悉这个模式对于理解面向对象的设计原则,包括"开-闭"原则(OCP)以及组合/聚合复用原则(CARP)都很有帮助。理解好这两个原则,有助于形成正确的设计思想和培养良好的设计风格。我是这样理解的:对一个事物进行抽象,得到了一个行为。 比如对Shape进行抽象,得到了Draw的行为。Draw是在哪里实现的?不是在它抽象而来的类Shape,而是在另外一个类实现的。哪个类呢?Drawing类。
Draw是从Shape抽象出来的行为,但是不在Shape中予以实现。这就是抽象和实现分离。
为什么要这样呢?因为Draw的方法可能不同,比如可以用实线,也可以用虚线。为了更好的隐藏变化,所以将其分离。
二、 桥梁模式的结构
桥梁模式【GOF95】是对象的结构模式,又称为柄体(Handle and Body)模式或接口(Interface)模式。下图所示就是一个实现了桥梁模式的示意性系统的结构图。
// Bridge pattern -- Structural example
using System;
// "Abstraction"
class Abstraction
// "Implementor"
abstract class Implementor
// "RefinedAbstraction"
class RefinedAbstraction : Abstraction
// "ConcreteImplementorA"
class ConcreteImplementorA : Implementor
// "ConcreteImplementorB"
class ConcreteImplementorB : Implementor
public class Client
// Bridge pattern -- Structural example
using System;
// "Abstraction"
class Abstraction
// "Implementor"
abstract class Implementor
// "RefinedAbstraction"
class RefinedAbstraction : Abstraction
// "ConcreteImplementorA"
class ConcreteImplementorA : Implementor
// "ConcreteImplementorB"
class ConcreteImplementorB : Implementor
public class Client
{
public static void Main( string[] args )
{
Abstraction abstraction = new RefinedAbstraction();
// Set implementation and call
abstraction.Implementor = new ConcreteImplementorA();
abstraction.Operation();
// Change implemention and call
abstraction.Implementor = new ConcreteImplementorB();
abstraction.Operation();
}
}
相关文章推荐
- 大家都来设计模式---桥梁(Bridge)模式
- 设计模式 - Bridge模式(桥梁模式)
- java设计模式(8):桥梁模式(Bridge)
- c++设计模式之Bridge桥梁模式.txt
- C++设计模式之十二--Bridge桥梁模式
- 设计模式C++之十一(Bridge桥梁模式)
- java设计模式之桥梁模式(Bridge)
- Java设计模式--桥梁模式【Bridge Pattern】
- 设计模式之Bridge模式(中文:桥梁模式)
- 设计模式C++学习笔记之十一(Bridge桥梁模式)
- "围观"设计模式(15)--结构型之桥梁模式(Bridge Pattern)
- 设计模式学习笔记--桥梁(Bridge)模式
- 设计模式——桥梁模式(Bridge)
- 设计模式——桥梁模式【Bridge Pattern】
- Java设计模式(13)——结构型模式之桥梁模式(Bridge)
- 设计模式之Bridge(桥梁)模式
- 设计模式13:Bridge Pattern (桥梁模式)
- 设计模式(9)Bridge桥梁设计模式
- 设计模式(八)桥梁模式(Bridge)