设计模式与实例代码:Bridge模式
来源:互联网 发布:编程模块都有哪些 编辑:程序博客网 时间:2024/06/06 13:20
意图/定义:将一组实现与另一组使用它们的对象分离,使得各自可以独立变化
问题:一个抽象类的多个派生类必须使用多个实现,但不能出现类爆炸
解决方案:为所有实现定义一个接口,供抽象类的所有派生类使用
参与者与协作者:抽象类的具体实现使用实现类的派生类,却无需知道自己使用的是具体哪个实现
效果:实现与使用实现的对象被解耦,提供了可抿生,客户对象无需操心实现问题
实现:将实现封装在一个抽象类后,在要实现的抽象基类中饭盒个实现的引用。
桥接模式是一个比较重要的结构性的设计模式,其结构十分类似于策略模式,与之不同之处在于抽象类之下的各种具体抽象是可以使用多种实现。
举一个不太适当的现实中的例子,以交通工具作为左边的抽象,不同的交通工具如汽车、卡车作为抽象的派生,不同类型的交通工具都需要发动机来驱动,但发动又有不同的品牌,因此交通工具就可以与发动机解耦,各自进行独立的变化。具体结构代码参见下表。
using System;namespace Bridge{ /// <summary> /// MainApp startup class for Structural /// Bridge Design Pattern. /// </summary> class MainApp { /// <summary> /// Entry point into console application. /// </summary> static void Main() { Abstraction car = new car(); // Set implementation and call car.Implementor = new ConcreteImplementorA(); car.drive(); // Change implemention and call car.Implementor = new ConcreteImplementorB(); car.drive(); Abstraction truck = new truck(); // Set implementation and call truck.Implementor = new ConcreteImplementorA(); truck.drive(); // Change implemention and call truck.Implementor = new ConcreteImplementorB(); truck.drive(); // Wait for user Console.ReadKey(); } } /// <summary> /// The 'Abstraction' class /// </summary> class Abstraction { protected Implementor implementor; // Property public Implementor Implementor { set { implementor = value; } } public virtual void drive() { implementor.drive(); } } /// <summary> /// The 'Implementor' abstract class /// </summary> abstract class Implementor { public abstract void drive(); } /// <summary> /// The 'RefinedAbstraction' class /// </summary> class car : Abstraction { public override void drive() { implementor.drive(); } } class truck : Abstraction { public override void drive() { implementor.drive(); } } /// <summary> /// The 'ConcreteImplementorA' class /// </summary> class ConcreteImplementorA : Implementor { public override void drive() { Console.WriteLine("ConcreteImplementorA drive"); } } /// <summary> /// The 'ConcreteImplementorB' class /// </summary> class ConcreteImplementorB : Implementor { public override void drive() { Console.WriteLine("ConcreteImplementorB drive"); } }}
- 设计模式与实例代码:Bridge模式
- 设计模式与实例代码:Facade模式
- 设计模式与实例代码:Adapter模式
- 设计模式与实例代码:Strategy模式
- 设计模式与实例代码:Decorator模式
- 设计模式与实例代码:Observer模式
- 设计模式实例与代码:Prototype模式
- 设计模式实例与代码:Builder模式
- 设计模式与实例代码:Composite模式
- 设计模式与实例代码:Visitor模式
- 设计模式与实例代码:Proxy模式
- 设计模式----Bridge模式
- 设计模式:Bridge模式
- 设计模式----Bridge模式
- 设计模式 -- Bridge模式
- 设计模式-Bridge模式
- 【设计模式】bridge模式
- 设计模式----Bridge模式
- 五大著名的免费SQL注入漏洞扫描工具
- hello gles!
- android应用开发笔记---Activity
- Spring提供的JUnit框架扩展
- 字符编码:UTF-8与GB2312之间的互换
- 设计模式与实例代码:Bridge模式
- Spring提供的JUnit框架扩展
- Spring提供的JUnit框架扩展
- python中eval, exec, execfile,和compile
- Spring事务配置的五种方式
- C++四舍五入问题
- 第八周实验报告 任务四(改)
- 让英语水平暴涨的超棒方法
- FRASM push的使用