设计模式十九(桥接模式)
1.个人感觉桥接模式就是把其他对象组合到自己的类中,以此来增加类的功能,这样的好处是丰富了类的功能,并且很多功能可以在其他类中写好,只是引用一下这个类即相当于自己的功能。它表现在一个类对另外一个类的拥有。其中又分弱包含和强包含,对应的就是聚合和组合。
2.它的适用背景是当一个系统可以从多个角度分类的时候,我们可以考虑用桥接模式,把抽象与它的实现分离。
3.UML图解
4.代码展示
namespace 桥接模式
{
class Program
{
static void Main(string[] args)
{
Abstraction ab = new RefinedAbstraction();
ab.SetImplementor(new ConcreteImplementorA());
ab.Operation();
ab.SetImplementor(new ConcreteImplementorB());
ab.Operation();
Console.Read();
}
}
class Abstraction
{
protected Implementor implementor;
public void SetImplementor(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的方法执行");
}
}
}