桥接模式:一些类之间的关系用关联(聚合、组合)来表示,而不是继承。

这个模式的解决的是类与类之间过多的继承关系,因为继承本身耦合度高的缺陷,过多使用继承会带来扩展困难,比如如果修改父类的功能就会直接影响到子类。而且也会因为继承的结构使得一些类的复用度不够高,出现代码重复的问题。

面向对象的设计模式 ——桥接模式

abstract class Implementor{
    public abstract void Operation();
}
class ConcreteImplementorA extends Implementor{
    public void Operation(){
        System.out.println("具体实现A的方法执行");
    }
}
class ConcreteImplementorB extends Implementor{
    public void Operation(){
        System.out.println("具体实现B的方法执行");
    }
}

 

class Abstraction{
    protected Implementor implementor;
    
    public void setImplementor(Implementor implementor){
        this.implementor = implementor;
    }
    
    public abstract void Operation();
}
class RefinedAbstraction extends Abstraction{
    public void Operation(){
        implementor.Operation();
    }
}
public class Test(){
    public static void main(String[] args){
        Abstraction ab = new RefinedAbstraction();
        
        ab.setImplementor(new ConcreteImplementorA());
        ab.Operation();

        ab.SetImplementor(new ConcreteImplementorB());
        ab.Operation();
    }
}

 

 

 

 

相关文章:

  • 2021-07-31
  • 2021-10-15
  • 2021-07-18
  • 2021-08-07
  • 2021-08-01
  • 2021-07-07
  • 2021-09-21
  • 2021-11-17
猜你喜欢
  • 2022-01-20
  • 2021-08-03
  • 2021-10-19
  • 2022-12-23
  • 2021-10-19
相关资源
相似解决方案