一、桥接模式介绍
桥接模式(bridge pattern) 的定义是:将抽象部分与它的实现部分分离,使它们都可以独立地变化。
桥接模式用一种巧妙的方式处理多层继承存在的问题,用抽象关联来取代传统的多层继承,将类之间的静态继承关系转变为动态的组合关系,使得系统更加灵活,并易于扩展,有效的控制了系统中类的个数 (避免了继承层次的指数级爆炸)。
二、桥接模式结构
- 抽象化(Abstraction)角色 :主要负责定义出该角色的行为 ,并包含一个对实现化对象的引用。
- 扩展抽象化(RefinedAbstraction)角色 :是抽象化角色的子类,实现父类中的业务方法,并通过组合关系调用实现化角色中的业务方法。
- 实现化(Implementor)角色 :定义实现化角色的接口,包含角色必须的行为和属性,并供扩展抽象化角色调用。
- 具体实现化(Concrete Implementor)角色 :给出实现化角色接口的具体实现。
三、使用场景
- 如果一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性,避免在两个层次之间建立静态的继承联系,通过桥接模式可以使它们在抽象层建立一个关联关系
- 对于那些不希望使用继承或因为多层次继承导致系统类的个数急剧增加的系统,桥接模式尤为适用
- 一个类存在两个独立变化的维度,且这两个维度都需要进行扩展
四、代码实例
1、Implementor
package com.xu.demo.bridgePattern;
/**
* 实现类接口
*/
public interface Implementor {
void operationImpl();
}
2、ConcreteImplementorA
package com.xu.demo.bridgePattern;
/**
* 具体实现类A
*/
public class ConcreteImplementorA implements Implementor {
@Override
public void operationImpl() {
System.out.println("Concrete ImplementorA operation.");
}
}
3、ConcreteImplementorB
package com.xu.demo.bridgePattern;
/**
* 具体实现类B
*/
public class ConcreteImplementorB implements Implementor {
@Override
public void operationImpl() {
System.out.println("Concrete ImplementorB operation.");
}
}
4、Abstraction
package com.xu.demo.bridgePattern;
/**
* 抽象类接口
*/
public abstract class Abstraction {
protected Implementor implementor;
public Implementor getImplementor() {
return implementor;
}
public void setImplementor(Implementor implementor) {
this.implementor = implementor;
}
public Abstraction(Implementor implementor) {
this.implementor = implementor;
}
public abstract void operation();
}
5、RefinedAbstraction
package com.xu.demo.bridgePattern;
/**
* 扩展类
*/
public class RefinedAbstraction extends Abstraction {
public RefinedAbstraction(Implementor implementor) {
super(implementor);
}
@Override
public void operation() {
implementor.operationImpl();
}
}
6、BridgePattern
package com.xu.demo.bridgePattern;
/**
* 桥接模式
*/
public class BridgePattern {
public static void main(String[] args) {
Abstraction abstraction = new RefinedAbstraction(new ConcreteImplementorA());
abstraction.operation(); // 输出: Concrete ImplementorA operation.
abstraction.setImplementor(new ConcreteImplementorB());
abstraction.operation(); // 输出: Concrete ImplementorB operation.
}
}
运行结果:
至此,一个简单的桥接模式的实例就完成了,好好学习认真体会,你也能成为IT高手,我们下回再见。