c#设计模式之桥梁模式

桥梁模式的用意是"将抽象化(Abstraction)与实现化(Implementation)脱耦,使得二者可以独立地变化"。这句话有三个关键词,也就是抽象化、实现化和脱耦。

类图如下:


Implementor

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

ConcreateImplementorA

 public class ConcreateImplementorA : Implementor
    {
        public override void Function()
        {
            Console.WriteLine("Function in ConcreateImplementorA");
        }
    }

ConcreateImplementorB

public class ConcreateImplementorB : Implementor
    {
        public override void Function()
        {
            Console.WriteLine("Function in ConcreateImplementorB");
        }
    }

Abstract

public abstract class Abstract
    {
        private Implementor implementor;
        public Abstract(Implementor imp)
        {
            this.implementor = imp;
        }
        public  void Function()
        {
            this.implementor.Function();
        }
        public abstract void Func();
    }

ConcreateAbstract

public class ConcreateAbstract : Abstract
    {
        public ConcreateAbstract(Implementor imp) : base(imp)
        {
        }

        public override void Func()
        {
        }
    }

调用

static void Main(string[] args)
        {
            ConcreateImplementorA concreateImp = new ConcreateImplementorA();
            ConcreateAbstract concreateAbstract = new ConcreateAbstract(concreateImp);

            concreateAbstract.Function();
            concreateAbstract.Func();
        }

优点:

  1. 使抽象和实现沿着各自的方向扩展,相互没有制约(比如Implementor需要增加一个实现类,而Abstract不必增加对应的实现类)

缺点:

  1. 使程序变复杂

源代码地址: 点击我下载 提取码: 2ms2

你可能感兴趣的:(c#设计模式之桥梁模式)