设计模式之桥接模式

2021-01-08  本文已影响0人  逍遥白亦

1. 定义

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

2. 特点

2.1 优点

2.2 缺点

由于聚合关系建立在抽象层,要求开发者针对抽象化进行设计与编程,能正确地识别出系统中两个独立变化的维度,这增加了系统的理解与设计难度。

3. 角色

4. 类图

桥接类图

5. 实现

package Bridge;

public interface Implementor {

    void operationImpl();

}

package Bridge;

public class ConcreteImplementor implements Implementor {

    @Override
    public void operationImpl() {
        System.out.println("具体实现化角色");
    }
}

package Bridge;

public abstract class Abstraction {

    protected Implementor implementor;

    public Abstraction(Implementor implementor) {
        this.implementor = implementor;
    }

    public abstract void operation();
}

package Bridge;

public class RefinedAbstraction extends Abstraction {

    public RefinedAbstraction(Implementor implementor) {
        super(implementor);
    }

    @Override
    public void operation() {
        System.out.println("扩展角色被调用");
        implementor.operationImpl();
    }
}

package Bridge;

public class Client {

    public static void main(String[] args) {
        Implementor implementor = new ConcreteImplementor();
        Abstraction abstraction = new RefinedAbstraction(implementor);
        abstraction.operation();
    }

}
上一篇下一篇

猜你喜欢

热点阅读