一、什么是桥接模式
桥接模式的作用是在一个模块中加入另一个模块使两个模块能够共同的工作,同时两个模块之间也不相互影响,每个模块都可以独立的更新。
例如一个手机的由硬件系统中需要加入软件才能够是实现功能,我们则把软件模型单独实现,软件的更新和硬件的改变两个之间互补影响,但需要同时工作才能使手机运行。
二、桥接模式的实现
1、桥接模式的实现模型
Abstraction和RefinedAbstraction作为抽象类分别表示两个不同的功能,他们可以独自扩展自己的功能相互不影响。
Abstraction作为一个链接两个类的功能。
2、桥接模式的代码实现
using System;
abstract class Implementor
{
public abstract void Operation();
}
class ConcretrImplementorA : Implementor
{
public override void Operation()
{
Console.WriteLine ("A method to realize");
}
}
class ConcretrimplementorB :Implementor
{
public override void Operation()
{
Console.WriteLine ("Implementation method 2");
}
}
class Abstration
{
protected Implementor implementor;
public void SetImplementor(Implementor implementor)
{
this.implementor = implementor;
}
public virtual void Operation()
{
implementor.Operation ();
}
}
class RefinedAbstration :Abstration
{
public override void Operation()
{
implementor.Operation ();
}
}
class MainClass
{
public static void Main (string[] args)
{
Abstration ab = new RefinedAbstration ();
ab.SetImplementor (new ConcretrImplementorA ());
ab.Operation();
ab.SetImplementor (new ConcretrimplementorB ());
ab.Operation ();
Console.ReadKey ();
}
}
运行结果: