java23种设计模式--桥接模式
定义
1.将抽象部分与实现部分分离,使它们都可以独立的变化。
2.将抽象和实现放在两个不同的类层次中,使它们可以独立地变化。——《Head First 设计模式》
UML
角色
- 抽象化角色: 抽象了类的基本功能。聚合一个实现化角色完成功能。
- 实现化角色接口: 一个类或者接口。定义实现化接口的基本功能。
- 具体实现化角色: 实现了实现化角色定义的功能,使得具体实现能脱离抽象部分而独立变化。
- 修正抽象化角色: 继承或者实现了抽象化角色,改善了抽象化角色的基本功能。使得抽象部分可以独立的变化
示例
/**
* desc : 抽象化角色
* Created by tiantian on 2018/10/8
*/
public abstract class Abstraction {
protected Implementor implementor;
public Abstraction(Implementor implementor) {
this.implementor = implementor;
}
public abstract void action();
}
/**
* desc : 实现化角色接口
* Created by tiantian on 2018/10/8
*/
public interface Implementor {
void actionImpl();
}
/**
* desc : 具体实现化角色实现
* Created by tiantian on 2018/10/8
*/
public class ConcreteImplementorA implements Implementor {
@Override
public void actionImpl() {
System.out.println("ConcreteImplementorA action");
}
}
/**
* desc : 具体实现化角色实现
* Created by tiantian on 2018/10/8
*/
public class ConcreteImplementorB implements Implementor {
@Override
public void actionImpl() {
System.out.println("ConcreteImplementorA action");
}
}
/**
* desc : 修正抽象化角色
* Created by tiantian on 2018/10/8
*/
public class RefinedAbstraction extends Abstraction{
public RefinedAbstraction(Implementor implementor) {
super(implementor);
}
@Override
public void action() {
super.implementor.actionImpl();
}
}
总结
抽象和具体是两个维度,如果两个维度都可能发生变化,那么了维护性和扩展性,桥梁模式将很适用这种情况。桥梁模式分离了抽象部分和实现部分,使得二者能独立的变化,抽象部分的扩展不会影响到具体实现,具体实现的变化也不会影响抽象部分。