模式定义
桥接模式(Bridge Pattern):将抽象部分与它的实现部分分离,使它们都可以独立地变化。它是一种对象结构型模式,又称为柄体(Handle and Body)模式或接口(Interface)模式。
当一个对象由多个对象组合而成,使用桥接模式能减少类数量。UML类图
- 抽象类(Abstraction) 定义一个成员变量(实现类接口类型) 和赋值方法
- 扩展抽象类(Refined Abstraction) 实现了在抽象类中定义的抽象业务方法,在扩充抽象类中可以调用 在实现类接口中定义的业务方法
- 实现类接口(Implementor) 实现部分的基本操作接口
具体实现类(Concrete Implement) 实现了实现类接口
代码结果
public static class BridgeApp { public static void Run() { Abstraction ab = new RefinedAbstraction(); ab.Implementor = new ConcreteImplementorA(); ab.Operation(); } } public class Abstraction { protected Implementor implementor; public Implementor Implementor { set { implementor = value; } } public virtual void Operation() { implementor.Operation(); } } public interface Implementor { void Operation(); } public class RefinedAbstraction : Abstraction { public override void Operation() { implementor.Operation(); } } public class ConcreteImplementorA : Implementor { public void Operation() { Console.WriteLine("ConcreteImplementorA Operation"); } } public class ConcreteImplementorB : Implementor { public void Operation() { Console.WriteLine("ConcreteImplementorB Operation"); } }
情景模式
现在智能手机品牌越来越多了,其实大家都明白好的手机都是那不同的部件组装下。这里假设手机主要CPU和内存。哈哈只需要修改CPU与内存就可以生产不同类型的手机
public static class BridgeApp { public static void Run() { PhoneOne phone1 = new PhoneOne(); phone1.Display(); PhoneTwo phone2 = new PhoneTwo(); phone2.Display(); } } public class PhoneOne { private CPU _cpu = new HPCPU(); private RAM _ram = new RAM128(); public void Display() { Console.WriteLine("Phone one:"); _cpu.Display(); _ram.Display(); Console.WriteLine("------------------------------------------"); } } public class PhoneTwo { private CPU _cpu = new HPCPU(); private RAM _ram = new RAM64(); public void Display() { Console.WriteLine("Phone two:"); _cpu.Display(); _ram.Display(); Console.WriteLine("------------------------------------------"); } } public abstract class CPU { public abstract void Display(); } public abstract class RAM { public abstract void Display(); } public class RAM64 : RAM { public override void Display() { Console.WriteLine("RMS size is 64"); } } public class RAM128 : RAM { public override void Display() { Console.WriteLine("RMS size is 128"); } } public class LestinaCPU : CPU { public override void Display() { Console.WriteLine("CPU Type is LestinaCPU"); } } public class HPCPU : CPU { public override void Display() { Console.WriteLine("CPU Type is HPCPU"); } }