1、定义
桥接模式是将抽象部分与它的实现部分分离,使它们都对立地变化。它是一种对象结构模式,又称为柄体(Handle and Body)模式或接口(Interface)模式。
2、优劣分析
(1)好处分析
(2)劣势分析
3、最佳实践
4、场景:
5、类图
6、代码实例
1 /** 2 * @author it-小林 3 * @desc 品牌 4 * @date 2021年07月21日 19:41 5 */ 6 public interface Brand { 7 8 void info(); 9 }
1 /** 2 * @author it-小林 3 * @desc 苹果品牌 4 * @date 2021年07月21日 19:43 5 */ 6 public class Apple implements Brand{ 7 @Override 8 public void info() { 9 System.out.print("苹果"); 10 } 11 }
1 /** 2 * @author it-小林 3 * @desc 联想品牌 4 * @date 2021年07月21日 19:42 5 */ 6 public class Lenovo implements Brand{ 7 8 @Override 9 public void info() { 10 System.out.print("联想"); 11 } 12 }
1 /** 2 * @author it-小林 3 * @desc 抽象的电脑类型类 4 * @date 2021年07月21日 19:44 5 */ 6 public abstract class Computer { 7 8 //组合, 品牌 9 protected Brand brand; 10 11 public Computer(Brand brand) { 12 this.brand = brand; 13 } 14 15 public void info(){ 16 //自带品牌 17 brand.info(); 18 } 19 }
1 /** 2 * @author it-小林 3 * @desc 4 * @date 2021年07月21日 19:46 5 */ 6 public class Desktop extends Computer{ 7 public Desktop(Brand brand) { 8 super(brand); 9 } 10 11 @Override 12 public void info() { 13 super.info(); 14 System.out.println("台式机"); 15 } 16 }
1 /** 2 * @author it-小林 3 * @desc 4 * @date 2021年07月21日 19:48 5 */ 6 public class Laptop extends Computer{ 7 8 public Laptop(Brand brand) { 9 super(brand); 10 } 11 12 @Override 13 public void info() { 14 super.info(); 15 System.out.println("笔记本"); 16 } 17 }
1 /** 2 * @author it-小林 3 * @desc 4 * @date 2021年07月21日 19:49 5 */ 6 public class Test { 7 8 public static void main(String[] args) { 9 //苹果笔记本 10 Computer computer = new Laptop(new Apple()); 11 computer.info(); 12 13 //联想台式机 14 Computer computer2 = new Desktop(new Lenovo()); 15 computer2.info(); 16 } 17 }
运行结果截图
原文:https://www.cnblogs.com/linruitao/p/15041100.html