1 基本概念
1、定义
- 桥接模式是将抽象部分与它的实现部分分离,使它们都可以独立地变化。
- 它是一种对象结构型模式,又称为柄体(Handle and Body)模式或接口(Interface)模式。
2、好处
- 桥接模式偶尔类似于多继承方案,但是多继承方案违背了类的单一职责原则,复用性比较差,类的个数也非常多,桥接模式是比多继承方案更好的解决方法。极大地减少了子类的个数,从而降低管理和维护的成本。
- 桥接模式提高了系统的可扩充性,在两个变化维度中任意扩展一个维度,都不需要修改原有系统。符合开闭原则,就像一座桥,可以把两个变化的维度连接起来。
3、劣势
- 桥接模式的引入会增加系统的理解与设计难度,由于聚合关联关系建立在抽象层,要求开发者针对抽象进行设计与编程。
- 桥接模式要求正确识别出系统中两个独立变化的维度,因此其使用范围具有一定的局限性。
2 代码
Brand
package bridge; // 品牌 public interface Brand { void info(); }
Apple
package bridge; // 苹果品牌 public class Apple implements Brand { @Override public void info() { System.out.print("苹果"); } }
Lenovo
package bridge; // 联想品牌 public class Lenovo implements Brand { @Override public void info() { System.out.print("联想"); } }
Computer
package bridge; // 抽象的电脑类型 public abstract class Computer { // 组合品牌——桥 protected Brand brand; public Computer() { } public Computer(Brand brand) { this.brand = brand; } public void info() { // 自带品牌 brand.info(); } } class Desktop extends Computer { public Desktop(Brand brand) { super(brand); } @Override public void info() { super.info(); System.out.println("台式机"); } } class Laptop extends Computer { public Laptop(Brand brand) { super(brand); } @Override public void info() { super.info(); System.out.println("笔记本"); } }
MyTest
package bridge; import org.junit.Test; public class MyTest { @Test public void test() { // 苹果笔记本 Computer computer1 = new Laptop(new Apple()); computer1.info(); // 联想台式机 Computer computer2 = new Desktop(new Lenovo()); computer2.info(); } }