【设计模式】桥接模式(Bridge)

tech2025-01-13  6

概述

桥接模式就是把事物和其具体实现分开,使他们可以各自独立的变化

适用性

将抽象化与实现化解耦,使得二者可以独立变化,像我们常用的 JDBC 桥 DriverManager 一样,JDBC 进行连接数据库的时候,在各个数据库之间进行切换,基本不需要动太多的代码,甚至丝毫不用动,原因就是 JDBC 提供统一接口,每个数据库提供各自的实现,用一个叫做数据库驱动的程序来桥接就行了

案例

public abstract class Clothing { public abstract void personDressCloth(Person person); } public class Jacket extends Clothing { public void personDressCloth(Person person) { System.out.println(person.getType() + "穿马甲"); } } public class Trouser extends Clothing { public void personDressCloth(Person person) { System.out.println(person.getType() + "穿裤子"); } } public abstract class Person { private Clothing clothing; private String type; public Clothing getClothing() { return clothing; } public void setClothing() { this.clothing = ClothingFactory.getClothing(); } public void setType(String type) { this.type = type; } public String getType() { return this.type; } public abstract void dress(); } public class Man extends Person { public Man() { setType("男人"); } public void dress() { Clothing clothing = getClothing(); clothing.personDressCloth(this); } } public class Lady extends Person { public Lady() { setType("女人"); } public void dress() { Clothing clothing = getClothing(); clothing.personDressCloth(this); } } public class Test { public static void main(String[] args) { Person man = new Man(); Person lady = new Lady(); Clothing jacket = new Jacket(); Clothing trouser = new Trouser(); jacket.personDressCloth(man); trouser.personDressCloth(man); jacket.personDressCloth(lady); trouser.personDressCloth(lady); } } // 输出 // 男人穿马甲 // 男人穿裤子 // 女人穿马甲 // 女人穿裤子
最新回复(0)