桥接模式是用于把抽象化与实现化解耦,使得二者可以独立变化。这种类型的设计模式属于结构性模式,它通过提供抽象化和实现化之间的桥接结构,来实现二者的解耦。
将抽象部分与实现部分分离,使得他们都可以独立的变化。
在有多种可能变化的情况下下,用继承会造成类爆炸的问题,扩展起来不灵活。
实现系统有可能有多个角度分类,每一中角度都可能变化。
//品牌
package FBridge; /** * @Author Zhou jian * @Date 2020 ${month} 2020/7/1 0001 15:05 */ public interface Brand { void info(); }//品牌实现类
package FBridge; /** * @Author Zhou jian * @Date 2020 ${month} 2020/7/1 0001 15:07 */ public class Apple implements Brand { @Override public void info() { System.out.println("苹果"); } } package FBridge; /** * @Author Zhou jian * @Date 2020 ${month} 2020/7/1 0001 15:06 */ public class Lenovo implements Brand { @Override public void info() { System.out.println("联想"); } }//电脑
package FBridge; /** * @Author Zhou jian * @Date 2020 ${month} 2020/7/1 0001 15:07 * 抽象的电脑 */ public abstract class Computer { //组合,品牌 protected Brand brand; 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("笔记本"); } } ```java package FBridge; /** * @Author Zhou jian * @Date 2020 ${month} 2020/7/1 0001 15:11 */ public class Test { public static void main(String[] args) { //苹果笔记本 Computer computer = new Laptop(new Apple()); computer.info(); //联想台式机 } }