设计模式之桥接模式

桥接模式(Bridge)是一种结构型设计模式。Bridge模式基于类的最小设计原则,通过使用封装、聚合及继承等行为让不同的类承担不同的职责。它的主要特点是把抽象(Abstraction)与行为实现(Implementation)分离开来,从而可以保持各部分的独立性以及应对他们的功能扩展。

桥接模式的角色和职责:

1.Client 调用端

这是Bridge模式的调用者。

2.抽象类(Abstraction)

抽象类接口(接口这货抽象类)维护队行为实现(implementation)的引用。它的角色就是桥接类。

3.Refined Abstraction

这是Abstraction的子类。

4.Implementor

行为实现类接口(Abstraction接口定义了基于Implementor接口的更高层次的操作)

5.ConcreteImplementor

Implementor的子类

 

桥接模式的UML图如下:

示例代码如下:

首先定义Implementor接口,其中定义了其实现类必须要实现的接口operation()

1 public interface Implementor {
2     public void operation();
3 }

下面定义Implementor接口的两个实现类:

1 public class ConcreateImplementorA implements Implementor {
2     @Override
3     public void operation() {
4         System.out.println("this is concreteImplementorA's operation...");
5     }
6 }
1 public class ConcreateImplementorB implements Implementor {
2     @Override
3     public void operation() {
4         System.out.println("this is concreteImplementorB's operation...");
5     }
6 }

 

下面定义桥接类Abstraction,其中有对Implementor接口的引用:

 1 public abstract class Abstraction {
 2     private Implementor implementor;
 3 
 4     public Implementor getImplementor() {
 5         return implementor;
 6     }
 7 
 8     public void setImplementor(Implementor implementor) {
 9         this.implementor = implementor;
10     }
11 
12     protected void operation(){
13         implementor.operation();
14     }
15 }

下面是Abstraction类的子类RefinedAbstraction:

1 public class RefinedAbstraction extends Abstraction {
2     @Override
3     protected void operation() {
4         super.getImplementor().operation();
5     }
6 }

下面给出测试类:

 1 public class BridgeTest {
 2     public static void main(String[] args) {
 3         Abstraction abstraction = new RefinedAbstraction();
 4 
 5         //调用第一个实现类
 6         abstraction.setImplementor(new ConcreateImplementorA());
 7         abstraction.operation();
 8 
 9         //调用第二个实现类
10         abstraction.setImplementor(new ConcreateImplementorB());
11         abstraction.operation();
12 
13     }
14 }

运行结果如下:

这样,通过对Abstraction桥接类的调用,实现了对接口Implementor的实现类ConcreteImplementorA和ConcreteImplementorB的调用。实现了抽象与行为实现的分离。

 

总结:

1.桥接模式的优点

(1)实现了抽象和实现部分的分离

桥接模式分离了抽象部分和实现部分,从而极大的提供了系统的灵活性,让抽象部分和实现部分独立开来,分别定义接口,这有助于系统进行分层设计,从而产生更好的结构化系统。对于系统的高层部分,只需要知道抽象部分和实现部分的接口就可以了。

(2)更好的可扩展性

由于桥接模式把抽象部分和实现部分分离了,从而分别定义接口,这就使得抽象部分和实现部分可以分别独立扩展,而不会相互影响,大大的提供了系统的可扩展性。

(3)可动态的切换实现

由于桥接模式实现了抽象和实现的分离,所以在实现桥接模式时,就可以实现动态的选择和使用具体的实现。

(4)实现细节对客户端透明,可以对用户隐藏实现细节。

2.桥接模式的缺点

(1)桥接模式的引入增加了系统的理解和设计难度,由于聚合关联关系建立在抽象层,要求开发者针对抽象进行设计和编程。

(2)桥接模式要求正确识别出系统中两个独立变化的维度,因此其使用范围有一定的局限性。

3.桥接模式的使用场景

(1)如果一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性,避免在两个层次之间建立静态的继承联系,通过桥接模式可以使它们在抽象层建立一个关联关系。

(2)抽象化角色和实现化角色可以以继承的方式独立扩展而互不影响,在程序运行时可以动态将一个抽象化子类的对象和一个实现化子类的对象进行组合,即系统需要对抽象化角色和实现化角色进行动态耦合。

(3)一个类存在两个独立变化的维度,且这两个维度都需要进行扩展。

(4)虽然在系统中使用继承是没有问题的,但是由于抽象化角色和具体化角色需要独立变化,设计要求需要独立管理这两者。

(5)对于那些不希望使用继承或因为多层次继承导致系统类的个数急剧增加的系统,桥接模式尤为适用

 

posted @ 2016-09-30 11:02  GloryLee  阅读(35109)  评论(0编辑  收藏  举报