6 Bridge模式 6.1 概述
Bridage模式就是把抽象部分和它的实现部分分离开来,让两者可独立变化。这里的抽象部分指的是一个概念层次上的东西,它的实现部分指的是实现这个东西的(功能)部分,分离就把实现部分从它要实现的抽象部分独立出来,自我封装成对象。
6.2 设计
思路简单理解就是:在类中抽离方法形成另一个类。比如对于动物狗,有行走功能。一般我们设计时,把狗设计成一个类,里面有方法“行走”。那么Bridge模式就是把“行走”方法从“狗”类中抽离出来,形成“行走”类,并在“狗”类中使用这个“行走”对象,实现行走功能。这样,“狗”类和“行走”类都可以独立变化。
6.3 实现
UML图:
示例代码为:
<!-- lang: cpp -->
using System;
namespace Example
{
class Example
{
[STAThread]
static void Main(string[] args)
{
Run r = new Run() ;//狗跑
Dog a = new Dog( r ) ;
Console.Write( "Dog can " ) ;
a.Move() ;
Fly f = new Fly() ;//鸟飞
Bird b = new Bird( f ) ;
Console.Write( "Bird can " ) ;
b.Move() ;
}
/// <summary>
/// 动物(抽象部分)
/// </summary>
public class Animal
{
protected Movement move = null ;
public Animal( Movement m )
{
move = m ;
}
public virtual void Move()
{
move.Move() ;
}
}
/// <summary>
/// 狗
/// </summary>
public class Dog : Animal
{
public Dog( Movement m ) : base( m ) {}
public override void Move()//狗运动
{
move.Move() ;
}
}
/// <summary>
/// 鸟
/// </summary>
public class Bird : Animal
{
public Bird( Movement m ) : base( m ) {}
public override void Move()//鸟运动
{
move.Move() ;
}
}
/// <summary>
/// 运动(实现部分)
/// </summary>
public class Movement
{
public Movement() {}
public virtual void Move()
{
Console.WriteLine( "Move" ) ;
}
}
/// <summary>
/// 具体的运动——跑
/// </summary>
public class Run : Movement
{
public Run() {}
public override void Move()
{
Console.WriteLine( "Run" ) ;
}
}
/// <summary>
/// 具体的运动——飞
/// </summary>
public class Fly : Movement
{
public Fly() {}
public override void Move()
{
Console.WriteLine( "Fly" ) ;
}
}
}
}
原址: http://www.cnblogs.com/fengchao/archive/2005/08/03/206971.html