桥接模式Bridge

简介

 Bridge 模式又叫作桥接模式,是构造型的设计模式之一。Bridge模式基于类的最小设计原则,经过使用封装,聚合以及继承等行为来让不一样的类承担不一样的责任。它的主要特色是把抽象(abstraction)与行为实现(implementation)分离开来,从而能够保持各部分的独立性以及应对它们的功能扩展。桥接模式是全部面向对象模式的基础,经过对桥接模式的学习来理解设计模式的思想。设计模式

类图

 

源码

开关(桥接)ide

public class Switch {
    public Device device; public Device getDevice() { return device; } public void setDevice(Device device) { this.device = device; } public void on() {
        System.out.println("开关打开");
    }

    public void off() {
        System.out.println("开关关闭");
    }
}

二插头学习

public class TwoSwitch extends Switch {
    @Override
    public void on() {
        System.out.println("二插座打开");
    }

    @Override
    public void off() {
        System.out.println("二插座关闭");
    }
}

三插头测试

public class ThreeSwitch extends  Switch {
    @Override
    public void on() {
        System.out.println("三插座打开");
    }

    @Override
    public void off() {
        System.out.println("三插座关闭");
    }
}

电器this

public interface Device {
    public void powerOn();

    public void powerOff();
}

电视spa

public class TV implements Device {
    public void powerOn() {
        System.out.println("打开电视");
    }

    public void powerOff() {
        System.out.println("关闭电视");
    }
}

电脑设计

public class PC implements Device {
    public void powerOn() {
        System.out.println("打开电脑");
    }

    public void powerOff() {
        System.out.println("关闭电脑");
    }
}

测试code

public class Main {
    public static void main(String[] args) {
        Switch twoSwitch = new TwoSwitch();
        Switch threeSwitch = new ThreeSwitch();
        Device pc = new PC();
        Device tv = new TV();
        twoSwitch.setDevice(tv);
        threeSwitch.setDevice(pc);
        twoSwitch.getDevice().powerOn();
        threeSwitch.getDevice().powerOn();
    }
}

结果对象

打开电视
打开电脑
相关文章
相关标签/搜索