设计模式学习—18桥接模式

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_33334951/article/details/102677197

桥接模式

UML

桥接模式

解释说明

  • 桥接模式:将抽象部分与它的实现部分分离,使它们都可以独立的变化。

代码实现

  • Implementor.class
package learn18;

public abstract class Implementor {
    public abstract void operation();
}
  • ConcreteImplementorA.class
package learn18;

public class ConcreteImplementorA extends Implementor {
    @Override
    public void operation() {
        System.out.println("执行方法A!");
    }
}
  • ConcreteImplementorB.class
package learn18;

public class ConcreteImplementorB extends Implementor {
    @Override
    public void operation() {
        System.out.println("执行方法B!");
    }
}
  • Abstraction.class
package learn18;

public abstract class Abstraction {
    protected Implementor implementor;

    public void setImplementor(Implementor implementor) {
        this.implementor = implementor;
    }

    public abstract void option();
}
  • RefinedAbstraction.class
package learn18;

public class RefinedAbstraction extends Abstraction {
    @Override
    public void option() {
        implementor.operation();
    }
}
  • Main.class
import learn18.*;

public class Main {

    public static void main(String[] args) throws Exception {
        Abstraction a = new RefinedAbstraction();
        a.setImplementor(new ConcreteImplementorA());
        a.option();

        Abstraction b = new RefinedAbstraction();
        b.setImplementor(new ConcreteImplementorB());
        b.option();
    }
}

参考资料

  • 大话设计模式

猜你喜欢

转载自blog.csdn.net/qq_33334951/article/details/102677197
今日推荐