桥接模式
1. 实现
- 找到两个维度(本次用类型和品牌举例)
- 对两个维度进行抽象
public interface Brand { void info(); } @Data @AllArgsConstructor @NoArgsConstructor public abstract class Computer { protected Brand brand; public void info() { brand.info(); } }
- 实现抽象类和接口
public class Apple implements Brand { public void info() { System.out.print("This is Apple "); } } public class Lenovo implements Brand { public void info() { System.out.print("This is Lenovo "); } } public class Desktop extends Computer { public Desktop(Brand brand) { super(brand); } public Desktop() { } @Override public void info() { super.info(); System.out.println("This is Desktop"); } } public class Laptop extends Computer { public Laptop() { } public Laptop(Brand brand) { super(brand); } @Override public void info() { super.info(); System.out.println("This is Laptop"); } }
- 测试
public class Main { public static void main(String[] args) { Computer appleLaptop = new Laptop(new Apple()); appleLaptop.info(); Computer lenovoDesktop = new Desktop(new Lenovo()); lenovoDesktop.info(); } }
2. 总结
-
优点:提高了系统的可扩展性 在两个变化维度中任意扩展不会影响到整个程序 符合开闭原则
-
缺点:适用范围具有一定局限性
-
如果系统中存在两个变化维度,且这两个维度都要扩展,适用桥接模式