桥接模式(Bridge)

桥接模式(Bridge,将抽象部分与它的实现部分分离,使它们独立地变化。

什么叫抽象与它的实现分离,这并不是说,让抽象类与其派生类分离,因为这没有任何意义。实现指的是抽象类和它的派生类用来实现自己的对象。

桥接模式的核心意图就是把这些实现独立出来,让它们各自地变化。这就使得每种实现的变化不会影响其他实现,从而达到应对变化的目的。

 

结构图


 

 

 //Implementor类
    abstract class Implementor
    {
        public abstract void Operation();
    }
    //ConcreteImplementorA和ConcreteImplementorB等派生类
    class ConcreteImplementorA:Implementor 
    {
        public override void Operation()
        {
            Console.WriteLine("具体实现A的方法执行");
        }
    }
    class ConcreteImplementorB : Implementor
    {
        public override void Operation()
        {
            Console.WriteLine("具体实现B的方法执行");
        }
    }
    //Abstraction类
    class Abstraction
    {
        protected Implementor implementor;
        public void SetImplementor(Implementor implementor)
        {
            this.implementor = implementor;
        }
        public virtual void Operation()
        {
            implementor.Operation();
        }
    }
    //RefinedAbstraction类
    class RefinedAbstraction : Abstraction
    {
        public override void Operation()
        {
            implementor.Operation();
        }
    }


客户端实现

 

static void Main(string[] args)
        {
            Abstraction ab = new RefinedAbstraction();

            ab.SetImplementor(new ConcreteImplementorA ());
            ab.Operation();

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

            Console.Read();
        }


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

 

合成/聚合复用原则(CARP)

尽量使用合成/聚合,尽量不要使用类继承。

在一个新的对象里面使用一些已有的对象,使之成为新对象的一部分,新对象通过向这些对象的委派达到复用已有功能的目的。

合成(Composition)和聚合(Aggregation)都是关联的特殊种类。聚合表示一种弱的‘拥有’关系,体现的是A对象可以包含B对象,但B对象不是A对象的一部分;合成则是一种强的‘拥有’关系,体现了严格的部分和整体的关系,部分和整体的生命周期一样。

优点:

优先使用对象的合成/聚合将有助于你保持每一个类被封装,并被集中在单个任务上。这样类和类继承层次会保持较小规模,并且不太可能增长为不可控制的庞然大物。

原文地址:https://www.cnblogs.com/rockywood/p/6655504.html