桥接模式简单实例

2020年5月8日 2708点热度 0人点赞 0条评论
内容目录

使用继承的的方式,缺点是添加功能是,上下层都需要改变;
同时为了避免为外界透露细节;
松耦合,避免两者出现静态的联系;
有接口和实现如下:

    public interface ITest
    {
        void A();
        void B();
    }

    public class T1 : ITest
    {
        public void A() { }

        public void B() { }
    }
    public class T2 : ITest
    {
        public void A() { }

        public void B() { }
    }

使用桥接器模式,添加一个新的类如下:

    public class Client
    {
        private ITest _Implementor;
        public ITest Implementor { get { return _Implementor; } set { _Implementor = value; } }
        public virtual void A()
        {
            _Implementor.A();
        }
        public virtual void B()
        {
            _Implementor.B();
        }
    }

实例化桥接器类型后,可以将其桥接到 T1 或者 T2,使用方法如下:

    class Program
    {
        static void Main(string[] args)
        {
            Client client = new Client();
            client.Implementor = new T1();
            client.A();
            client.B();

            client.Implementor = new T2();
            client.A();
            client.B();
        }
    }

工厂模式在于提供实例;
桥接在于在结构上提供适配。

适配器模式和桥接模式有些相似。

痴者工良

高级程序员劝退师

文章评论