简单案例:操作笔记本电脑办公或者打游戏,笔记本电脑有不同的类型,比如:游戏本、轻薄本等,也有很多品牌:联想、戴尔、华硕等。
UML类图:
代码实现:
public class Computer { public void work() { System.out.println("办公"); } public void playGame(){ System.out.println("打游戏"); } }
public class GameComputer extends Computer{ @Override public void work() { System.out.println("游戏本办公"); } @Override public void playGame() { System.out.println("游戏打游戏"); } }
public class PortableComputer extends Computer{ @Override public void work() { System.out.println("轻薄本办公"); } @Override public void playGame() { } }
public class LenovoGameComputer extends GameComputer{ @Override public void work() { System.out.println("联想游戏本办公"); } @Override public void playGame() { System.out.println("联想游戏本打游戏"); } }
public class LenovoPortableComputer extends PortableComputer{ @Override public void work() { System.out.println("联想轻薄本办公"); } @Override public void playGame() { } }
传统方式分析:
2.1 简介:
2.2 原理图:
说明:
案例 UML 类图:
代码实现:
public interface ComputerBrand { public void work(); public void playGame(); }
public class DellBrandImpl implements ComputerBrand{ @Override public void work() { System.out.println("戴尔电脑办公"); } @Override public void playGame() { System.out.println("戴尔电脑打游戏"); } }
public class LenovoBrandImpl implements ComputerBrand{ @Override public void work() { System.out.println("联想电脑办公"); } @Override public void playGame() { System.out.println("联想电脑打游戏"); } }
public abstract class Computer { private ComputerBrand brand; public Computer(ComputerBrand brand) { this.brand = brand; } protected void work() { brand.work(); } protected void playGame() { brand.playGame(); } }
public class GameComputer extends Computer{ public GameComputer(ComputerBrand brand) { super(brand); } @Override protected void work() { super.work(); System.out.println("电脑类型:游戏本"); } @Override protected void playGame() { super.playGame(); System.out.println("电脑类型:游戏本"); } }
public class PortableComputer extends Computer { public PortableComputer(ComputerBrand brand) { super(brand); } @Override protected void work() { super.work(); System.out.println("电脑类型:轻薄本"); } @Override protected void playGame() { super.playGame(); System.out.println("电脑类型:轻薄本"); } }
public class TestDemo { public static void main(String[] args) { Computer comp1 = new GameComputer(new LenovoBrandImpl()); comp1.playGame(); comp1.work(); System.out.println("*************************"); Computer comp2 = new GameComputer(new DellBrandImpl()); comp2.playGame(); comp2.work(); } }
桥接模式分析:
桥接模式使用场景:
1. JDBC 驱动程序
2. 银行转账
转账类型:柜台转账、网银转账、ATM机转账
用户类型:普通用户、VIP用户