Android的开发之&java23中设计模式------桥接模式

桥接模式

桥接模式是将抽象部分与它的实现部分分离,使它们都可以独立地变化。它是一种对象结构型模式,又称为柄体(Handle and Body)模式或接口(Interface)模式。

public class BridgeMethodActivity extends AppCompatActivity {
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bridge_method);

        Implementor implementor=new ConcreteImplementorA();
        RefinedAbstraction abstraction=new RefinedAbstraction(implementor);
        abstraction.operation();
        abstraction.otherOperation();
    }
}
public abstract class Abstraction {
    //持有一个Implementor对象,形成聚合关系
    protected Implementor implementor;

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

    //可能需要转调实现部分的具体实现
    public void operation(){
        implementor.operationImpl();
    }
}

public class ConcreteImplementorA implements Implementor {
    @Override
    public void operationImpl() {
        System.out.print("具体实现A");
    }
}
public class ConcreteImplementorB implements Implementor {
    @Override
    public void operationImpl() {
        System.out.print("具体实现B");
    }
}
public interface Implementor {
    //实现抽象部分需要的某些具体功能
    void operationImpl();
}
public class RefinedAbstraction extends Abstraction {
    public RefinedAbstraction(Implementor implementor) {
        super(implementor);
    }

    public void otherOperation(){
        // 实现一定的功能,可能会使用具体实现部分的实现方法,
        // 但是本方法更大的可能是使用 Abstraction 中定义的方法,
        // 通过组合使用 Abstraction 中定义的方法来完成更多的功能
        System.out.print("其他实现");
    }
}
应用场景
  1、如果你不希望在抽象和实现部分采用固定的绑定关系,可以采用桥接模式,来把抽象和实现部分分开,然后在程序运行期间来动态的设置抽象部分需要用到的具体的实现,还可以动态切换具体的实现。
  2、如果出现抽象部分和实现部分都应该可以扩展的情况,可以采用桥接模式,让抽象部分和实现部分可以独立的变化,从而可以灵活的进行单独扩展,而不是搅在一起,扩展一边会影响到另一边。
  3、如果希望实现部分的修改,不会对客户产生影响,可以采用桥接模式,客户是面向抽象的接口在运行,实现部分的修改,可以独立于抽象部分,也就不会对客户产生影响了,也可以说对客户是透明的。
  4、如果采用继承的实现方案,会导致产生很多子类,对于这种情况,可以考虑采用桥接模式,分析功能变化的原因,看看是否能分离成不同的纬度,然后通过桥接模式来分离它们,从而减少子类的数目。

github地址:https://github.com/zyj18410105150/DesignMode


猜你喜欢

转载自blog.csdn.net/jie1123161402/article/details/80383428
今日推荐