您的位置:首页 > 其它

设计模式之桥梁(Bridge)模式

2012-03-01 12:14 351 查看

一、 桥梁(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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: