title: 桥接模式
date: 2021-07-30 21:45:40
tags:
可将一个大类或一系列紧密相关的类拆分为抽象和实现两个独立的层次结构,从而能在开发时分别使用。
某户人家买了一个小米精灵,想把已经有的电视,电灯等电器接入到小米精灵中,使小米精灵成为一个终端,各自的遥控器小米精灵达到控制各自电器的功能。
// 抽象化角色 遥控器类 public abstract class Control { protected Device device; public Control(Device device) { this.device = device; } public abstract void up(); public abstract void down(); public abstract void turnOn(); public abstract void turnOff(); } // 扩展抽象化画角色 public class AudioControl extends Control { public AudioControl(Device device) { super(device); } @Override public void up() { if (device.isEnable()) { device.setNumber(device.getNumber() + 1); System.out.println("调高声音,现在是"+device.getNumber()); } } @Override public void down() { if (device.isEnable()) { device.setNumber(device.getNumber() - 1); System.out.println("调低声音,现在是"+device.getNumber()); } } @Override public void turnOn() { device.enable(); device.setNumber(60); System.out.println("开机"); } @Override public void turnOff() { device.disable(); System.out.println("关机"); } } public class ConditionControl extends Control { public ConditionControl(Device device) { super(device); } @Override public void up() { if (device.isEnable()) { device.setNumber(device.getNumber() + 1); System.out.println("调高温度,现在是" + device.getNumber()); } } @Override public void down() { if (device.isEnable()) { device.setNumber(device.getNumber() - 1); System.out.println("调低温度,现在是" + device.getNumber()); } } @Override public void turnOn() { device.enable(); device.setNumber(25); System.out.println("开空调"); } @Override public void turnOff() { device.disable(); System.out.println("关空调"); } } // 实现化角色 public interface Device { boolean isEnable(); void enable(); void disable(); int getNumber(); void setNumber(int num); } // 具体实现化角色 public class Audio implements Device { private boolean status; private int number; @Override public boolean isEnable() { return status; } @Override public void enable() { System.out.println("音响开机了"); this.status = true; } @Override public void disable() { System.out.println("音响关机了"); this.status = false; } @Override public int getNumber() { System.out.println("现在是" + number + "音量大小"); return this.number; } @Override public void setNumber(int num) { System.out.println("已设置音量为" + num); this.number = num; } } public class AirCondition implements Device { private boolean status; private int number; @Override public boolean isEnable() { return status; } @Override public void enable() { System.out.println("空调开机了"); this.status = true; } @Override public void disable() { System.out.println("空调关机了"); this.status = false; } @Override public int getNumber() { System.out.println("现在是" + number + "温度"); return this.number; } @Override public void setNumber(int num) { System.out.println("已设置温度为" + num); this.number = num; } }