桥接模式(Bridge Pattern):将抽象部分与其实现部分分离,使它们都可以独立地变化。它是一种对象结构型模式,又称为柄体(Handle and Body)模式或接口(Interface)模式。桥接模式用一种巧妙的方式处理多层继承存在的问题。桥接模式采用抽象关联取代了传统的多层继承,将类之间的静态继承关系转换为动态的对象组合关系,使得系统更加灵活,并易于扩展,同时有效控制了系统中类的个数。
合成/聚合复用原则(CARP),尽量使用合成/聚合,尽量不要使用类继承。[J&DP]
- //首先,我们定义一个接口Implementor,它表示实现部分的接口
- public interface Implementor {
- void operationImpl();
- }
-
- //然后,我们创建两种实现这个接口的具体类:
- public class ConcreteImplementorA implements Implementor {
- @Override
- public void operationImpl() {
- System.out.println("ConcreteImplementorA operationImpl()");
- }
- }
-
- public class ConcreteImplementorB implements Implementor {
- @Override
- public void operationImpl() {
- System.out.println("ConcreteImplementorB operationImpl()");
- }
- }
-
- //接下来,我们定义一个抽象类Abstraction,它包含一个对Implementor的引用:
- public abstract class Abstraction {
- protected Implementor implementor;
-
- public Abstraction(Implementor implementor) {
- this.implementor = implementor;
- }
-
- public void operation() {
- implementor.operationImpl();
- }
- }
-
- //现在,我们创建两个继承自Abstraction的具体类,每个都接受一个特定的Implementor类型:
-
- public class RefinedAbstractionA extends Abstraction {
- public RefinedAbstractionA(Implementor implementor) {
- super(implementor);
- }
- }
-
- public class RefinedAbstractionB extends Abstraction {
- public RefinedAbstractionB(Implementor implementor) {
- super(implementor);
- }
- }
-
- //最后,在客户端代码中,我们可以根据需要组合抽象部分和实现部分:
- public class Client {
- public static void main(String[] args) {
- Implementor implementorA = new ConcreteImplementorA();
- Implementor implementorB = new ConcreteImplementorB();
-
- Abstraction abstractionA1 = new RefinedAbstractionA(implementorA);
- Abstraction abstractionA2 = new RefinedAbstractionA(implementorB);
-
- Abstraction abstractionB1 = new RefinedAbstractionB(implementorA);
- Abstraction abstractionB2 = new RefinedAbstractionB(implementorB);
-
- // 使用不同的组合调用operation
- abstractionA1.operation();
- abstractionA2.operation();
- abstractionB1.operation();
- abstractionB2.operation();
- }
- }