桥接设计模式:

应用场景:

业务背景:

桥接模式图:

光猫桥接模式怎么设置(路由器设置桥接模式)(1)

核心组成:

实现步骤:

public interface Memory {  public void addMemory();}

  • 定义ConcreteImplementor,这里指具体的内存
public class Memory6G implements Memory {  @Override  public void addMemory() {    System.out.println("6G内存");  }}public class Memory8G implements Memory {  @Override  public void addMemory() {    System.out.println("8G内存");  }}

  • 定义Abstraction手机抽象类
public abstract class Phone {  public Memory memory;  public void setMemory(Memory memory) {    this.memory = memory;  }  public abstract void buyPhone();}

  • 定义Refined Abstraction(具体的手机品牌)
public class HuaWei extends Phone {  @Override  public void buyPhone() {    System.out.println("购买de华为手机-");    memory.addMemory();  }}public class XiaoMi extends Phone {  @Override  public void buyPhone() {    System.out.println("购买de小米手机-");    memory.addMemory();  }}

  • 上下文应用
public class BridgeContext {  public static void main(String[] args) {    Phone huaWei = new HuaWei();    huaWei.setMemory(new Memory6G());    huaWei.buyPhone();    huaWei.setMemory(new Memory8G());    huaWei.buyPhone();    Phone xiaomi = new XiaoMi();    xiaomi.setMemory(new Memory6G());    xiaomi.buyPhone();    xiaomi.setMemory(new Memory8G());    xiaomi.buyPhone();  }}

桥接模式的优点:

  • 抽象和实现的分离.
  • 优秀的扩展能⼒,符合开闭原则

桥接模式的缺点:

  • 增加系统的理解与设计难度
  • 使用聚合关联关系建立在抽象层,要求开发者针对抽象 进⾏设计与编程,比如抽象类汽车,⾥面聚合了颜⾊类,有点像对象适配器