设计模式读书笔记-桥接模式

2016-08-21
读书笔记
  • 定义:将抽象和实现解耦,使得两者可以独立地变化。
  • 手机品牌(品牌A、品牌B)与手机软件(游戏、通讯录)是聚合关系
  • 手机品牌包含手机软件:品牌<>——-软件
  • 代码:
public interface Soft {
    public void softRun();
}

public class SoftAddressList implements Soft{
    public void softRun() {
        System.out.println("手机通讯录运行");
    }
}

public class SoftGame implements Soft{
    public void softRun() {
        System.out.println("手机游戏开始运行");
    }
}

public abstract class Brand {
    protected Soft soft;//或通过带参构造方法设置soft

    public void setSoft(Soft soft){
        this.soft = soft;
    }
    public abstract void brandRun();
}

public class BrandA extends Brand{
    public void brandRun() {
        soft.softRun();
    }
}

public class BrandB extends Brand{
    public void brandRun() {
        soft.softRun();
    }
}

public class Client {

    public static void main(String[] args){

        Brand brandA = new BrandA();
        brandA.setSoft(new SoftGame());
        brandA.brandRun();

        brandA.setSoft(new SoftAddressList());
        brandA.brandRun();


        Brand brandB = new BrandB();
        brandB.setSoft(new SoftGame());
        brandB.brandRun();

        brandB.setSoft(new SoftAddressList());
        brandB.brandRun();
    }
}

Kommentare: