桥接设计模式

1、什么是桥接模式

​ 桥接模式是将抽象部分和它的实现部分分离,使它们能够独立变化。

2、代码

2.1、Display定义结构的类
public class Display {
    private DisplayImpl displayImpl; //聚合具体实现类

    public Display(DisplayImpl displayImpl){
        this.displayImpl = displayImpl;
    }

    public  void open(){
        displayImpl.rawOpen();
    }

    public  void print(){
        displayImpl.rawPrint();
    }

    public  void close(){
        displayImpl.rawClose();
    }

    public final void display(){
        open();
        print();
        close();
    }
}
2.2、CountDisplay类,继承了Display,添加新的功能(print多次)
public class CountDisplay extends Display {

    public CountDisplay(DisplayImpl displayImpl) {
        super(displayImpl);
    }

    public  void multiDisplay(int times){
        open();
        for (int i = 0; i < times; i++) {
            print();
        }
        close();
    }
}
2.3、DisplayImpl,具体实现的父类
public abstract class DisplayImpl {

    public abstract void  rawOpen();

    public abstract  void rawPrint();

    public abstract  void rawClose();
}
2.4、StringDisplayImpl类,具体实现
public class StringDisplayImpl extends DisplayImpl{

    private String string;

    private int width;

    public StringDisplayImpl(String string){
        this.string = string;
        this.width= string.getBytes().length;
    }

    @Override
    public void rawOpen() {
        printLine();
    }

    @Override
    public void rawPrint() {
        System.out.println("|"+string+"|");
    }

    @Override
    public void rawClose() {
        printLine();
    }

    private void printLine(){
        System.out.print("+");
        for (int i = 0; i < width; i++) {
            System.out.print("-");
        }
        System.out.println("+");
    }
}
2.5、MainTest类,测试用
public class MainTest {
    public static void main(String[] args) {
        Display display = new Display(new StringDisplayImpl("Hello ,China."));
        Display display1 = new Display(new StringDisplayImpl("Hello ,world."));
        CountDisplay display2 = new CountDisplay(new StringDisplayImpl("Hello ,universe."));

        display.display();
        display1.display();
        display2.display();
        display2.multiDisplay(5);
    }
}

3、优点

​ 抽象和实现分离,可扩展,解耦。

​ 抽象的添加和修改不影响实现,实现的修改不会影响的抽象的结构。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值