设计模式--桥接模式

将抽象部分与它的实现部分分离,使它们都可以独立地变化。
抽象与它的实现分离,并不是说让抽象类与其派生类分离,因为这没有任何意义,实现指的是抽象类和它的派生类用来实现自己的对象。

实现系统可能有多角度分类,每一种分类都有可能变化,那么就把这种多角度分离出来让它们独立变化,减少它们之间的耦合。

基本代码:

//抽象基类

class Abstraction
{
protected Implementor implementor;
public void SetImpementor(Implementor implementor)
{
this.implementor = implementor;
}

public virtual void Operation()
{
implementor.Operation();
}

}

//抽象基类的一个实现

class RefinedAbstraction:Abstraction
{
public override void Operation()
{
implementor.Operation();
}
}

//具体实现的基类

abstract class Implementor
{
public abstract void Operation();
}

//具体实现

class ConcreteImplementorA : Implementor
{
public override void Operation()
{
Console.WriteLine("具体实现A的方法执行");
}
}

class ConcreteImplementorB : Implementor
{
public override void Operation()
{
Console.WriteLine("具体实现B的方法执行");
}
}

调用:

Abstraction ab = new RefinedAbstraction();
ab.SetImpementor(new ConcreteImplementorA());
ab.Operation();

ab.SetImpementor(new ConcreteImplementorB());
ab.Operation();

//松耦合的程序

//手机软件抽象类

abstract class HandsetSoft
{
public virtual void Run(HandsetBrand hb)
{
Console.Write(hb.GetType().Name+":");
}
}

//手机游戏

class HandsetGame:HandsetSoft
{
public override void Run(HandsetBrand hb)
{
base.Run(hb);
Console.WriteLine("运行手机游戏");
}
}

//手机通讯录

class HandsetAddressList:HandsetSoft
{
public override void Run(HandsetBrand hb)
{
base.Run(hb);
Console.WriteLine("运行手机通讯录");
}
}

//手机品牌抽象类

abstract class HandsetBrand
{
protected HandsetSoft soft;
public void SetHandsetSoft(HandsetSoft soft)
{
this.soft = soft;
}
public virtual void Run(HandsetBrand hb)
{
this.soft.Run(hb);
}
}

//手机品牌M

class HandsetBrandM:HandsetBrand
{
}

//手机品牌N

class HandsetBrandN:HandsetBrand
{
}

调用:

HandsetGame game = new HandsetGame();
HandsetAddressList addressList = new HandsetAddressList();

HandsetBrand hb = new HandsetBrandM();
hb.SetHandsetSoft(game);
hb.Run(hb);
hb.SetHandsetSoft(addressList);
hb.Run(hb);

hb = new HandsetBrandN();
hb.SetHandsetSoft(game);
hb.Run(hb);
hb.SetHandsetSoft(addressList);
hb.Run(hb);

原文地址:https://www.cnblogs.com/buzhidaojiaoshenme/p/6731478.html