Unity学习笔记:设计模式-BRIDGE(桥接)

关键词:连接两端的变化

两个父类的派生类存在组合关系 排列组合的情况,其中一个父类调用另一个父类的方法 让子类继承,用以形成连接。

意图

将抽象部分(主体的成员)与它的实现部分分离,使它们都可以独立地变化。

用性:

• 你不希望在抽象和它的实现部分之间有一个固定的绑定关系。 例如这种情况可能是因为,

在程序运行时刻实现部分应可以被选择或者切换。

• 类的抽象以及它的实现都应该可以通过生成子类的方法加以扩充。这时 B r i d g e模式使你可以对不同的抽象接口和实现部分进行组合,并分别对它们进行扩充。

• 对一个抽象的实现部分的修改应对客户不产生影响,即客户的代码不必重新编译。

• 正如在意图一节的第一个类图中所示的那样,有许多类要生成。这样一种类层次结构说

明你必须将一个对象分解成两个部分。 R u m b a u g h称这种类层次结构为“嵌套的泛化”

(nested generalizations) 。

• 你想在多个对象间共享实现(可能使用引用计数) ,但同时要求客户并不知道这一点。

案例:(在黑板或者纸上 花一个图形)

图形

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace dp_Bridge
{
    public abstract class 图形
    {
        public 输出位置类 implemetor;
        virtual  public void Write()//
        {
            implemetor.Draw();
        }
    }
}

圆形 (矩形同)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace dp_Bridge
{
    public class 圆形 : 图形
    {
        public override void Write()
        {
            Console.WriteLine(" 图形 圆形 ");
            implemetor.Draw();
            
        }
    }
}

调用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace dp_Bridge
{
    class Program
    {
        static void Main(string[] args)
        {
            //在纸上画圆形
            //图形 obj = new 圆形();
            //obj.implemetor=new 纸上();
            //obj.Write();
            //Console.Read();
            //在黑板上 画矩形
            图形 obj = new 矩形();
            obj.implemetor = new 黑板();
            obj.Write();
            Console.Read();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/huanyu0127/article/details/107805312