设计模式学习笔记——桥接模式(Bridge)

1.特点:使继承关系更改为组合关系,使两者可独立变化。(未雨绸缪)

2.概念:将抽象部分与它的实现部分分离,使它们都可以独立地变化。

3.类图:

4.程序实现:

    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的方法执行");
        }
    }
    abstract 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();
        }
    }
    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();
        }
    }

  

原文地址:https://www.cnblogs.com/ice-baili/p/4710336.html