设计模式——桥接模式

来源:互联网 发布:c专家编程电子书 编辑:程序博客网 时间:2024/06/09 23:53

BRIDGE桥接模式

 

1、 意图

将抽象部分与它的实现部分分离,使它们都可以独立地变化。

2、 适用性

以下一些情况下使用Bridge模式:

  • 你不希望在抽象和它的实现部分之间有一个固定的绑定关系。
  • 类的抽象以及它的实现都应该通过生成子类的方法加以扩充。这时Bridge模式使你可以对不同的抽象接口和实现部分进行组合,并分别对它们进行扩充。
  • 对一个抽象的实现部分的修改应对客户不产生影响,即客户的代码不必重新编译。

3、 结构


4、 参与者

  •  Abstraction

——定义抽象类的接口。

——维护一个指向Implementor类型对象的指针。

  •  RefinedAbstraction

——扩充由Abstraction定义的接口

  • Implementor

——定义实现了的接口,该接口不一定要与Abstraction的接口完全一致;事实上这两个接口可以完全不同。一般来讲,Implementor接口仅提供基本操作,而Abstraction则定义了基于这些基本操作的较高层次的操作。

  •  ConcreteImplementor

——实现Implementor接口并定义它的具体实现。

5、 协作

AbstractClass将client的请求转发给它的Implementor对象

6、 效果

Bridge模式有以下一些优点:

1)  分离接口及其实现部分;一个实现未必不变地绑定在一个接口上。抽象类的实现可以在运行时刻进行配置,一个对象甚至可以在运行时刻改变它的实现。将Abstraction与Implementor分离有助于降低对实现部分编译时刻的依赖,当改变一个实现类时,并不需要重新编译Abstraction类和它的客户程序。

2)  提高可扩充性;你可以独立地对Abstraction和Implementor层次结构进行扩充。

3)  实现细节对客户透明;你可以对客户隐藏实现细节。

7、 示例

Implementor

package com.examples.pattern.bridge;/** * 定义实现部分的接口,可以与抽象部分接口的方法不一样 */public interface Implementor {public void operationImpl();}

ConcreteImplementor

package com.examples.pattern.bridge;/** * 真正的具体实现对象 */public class ConcreteImplementorA implements Implementor {@Overridepublic void operationImpl() {System.out.println("ConcreteImplementorA's Operation");}}
package com.examples.pattern.bridge;public class ConcreteImplementorB implements Implementor {@Overridepublic void operationImpl() {System.out.println("ConcreteImplementorB's Operation");}}

Abstraction

package com.examples.pattern.bridge;/** * 定义抽象部分的接口 */public abstract class Abstraction {/** * 持有一个实现部分的对象 */protected Implementor impl;/** * 构造方法,传入实现部分的对象 * @param impl实现部分的对象 */public Abstraction(Implementor impl) {this.impl = impl;}public void operation(){impl.operationImpl();}}

RefinedAbstraction

package com.examples.pattern.bridge;/** * 扩充由Abstraction定义的接口功能 */public class RefinedAbstraction extends Abstraction {public RefinedAbstraction(Implementor impl) {super(impl);}public void otherOperation(){}}
Client

package com.examples.pattern.bridge;public class Client {/** * @param args */public static void main(String[] args) {Implementor impl_a = new ConcreteImplementorA();Implementor impl_b = new ConcreteImplementorB();Abstraction abstraction_1 = new RefinedAbstraction(impl_a);Abstraction abstraction_2 = new RefinedAbstraction(impl_b);abstraction_1.operation();abstraction_2.operation();}}

8、 相关模式

 AbstractFactory模式可以用来创建和配置一个特定的Bridge模式。

Adapter模式用来帮助无关的类协同工作,它通常在系统设计后才会被使用。然而,Bridge模式则是在系统开始时就被使用,它使得抽象接口和实现部分独立进行改变。

原创粉丝点击