八、桥接模式--结构模式(Structural Pattern)

桥梁模式:将抽象化(Abstraction)与实现化 (Implementation)脱耦,使得二者可以独立地变化.

桥梁模式类图:

  抽象化(Abstraction)角色:抽象化给出的定义,并保存 一个对实现化对象的引用。  

  修正抽象化(Refined Abstraction)角色:扩展抽象化角 色,改变和修正父类对抽象化的定义。  

  实现化(Implementor)角色:这个角色给出实现化角色的接口,但不给出具体的实现。必须指出的是,这个接口不一定和抽象化角色的接口定义相同,

  实际上,这两个接口可以非常不一样。实现化角色应当只给出底层操作,而抽象化角色应当只给出基于底层操作的更高一层的操作。  

  具体实现化(Concrete Implementor)角色:这个角色 给出实现化角色接口的具体实现。

示例代码:

class Program
    {
        static void Main(string[] args)
        {
            Abstraction abstraction = new RefinedAbstraction();
            abstraction.Implementor = new ConcreteImplementorA();
            abstraction.Operation();
            abstraction.Implementor = new ConcreteImplementorB();
            abstraction.Operation();
            Console.ReadKey();
        }
        class Abstraction
        {
            protected Implementor implementor;
            public Implementor Implementor
            {
                set { implementor = value; }
            }

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

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

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

        class ConcreteImplementorA : Implementor
        {
            public override void Operation()
            {
                Console.WriteLine("ConcreteImplementorA Operation");
            }
        }

        class ConcreteImplementorB : Implementor
        {
            public override void Operation()
            {
                Console.WriteLine("ConcreteImpletementB Operation");
            }
        }
    }
View Code

运行结果:

   如果一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性,避免在两个层次之间建立静态的联系。  

  设计要求实现化角色的任何改变不应当影响客户端,或者说实现化角色的改变对客户端是完全透明的。  

  一个构件有多于一个的抽象化角色和实现化角色,系统需 要它们之间进行动态耦合。  

   虽然在系统中使用继承是没有问题的,但是由于抽象化角色和具体化角色需要独立变化,设计要求需要独立管理这两者。

posted @ 2016-02-19 16:47  mopheify  阅读(311)  评论(0编辑  收藏  举报