桥接模式Bridge

简介

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

类图

源码

开关(桥接)

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("三插座关闭");
    }
}

电器

public interface Device {
    public void powerOn();

    public void powerOff();
}

电视

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("关闭电脑");
    }
}

测试

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();
    }
}

结果

打开电视
打开电脑
原文地址:https://www.cnblogs.com/manusas/p/7485727.html