定义
桥接模式(Bridge Pattern):将抽象部分与它的实现部分分离,使它们都可以独立地变化。它是一种对象结构型模式,又称为柄体(Handle and Body)模式或接口(Interface)模式。
UML图描述
桥接模式主要包含四种角***r>1.Abstraction:抽象类
2.RefinedAbstraction:扩充抽象类
3.Implementor:实现类接口
4.ConcreteImplementor:具体实现类
此场景是游戏中有人物和服饰,人物和服饰都是可以独立变化的,所以此场景用桥接模式解决。
代码实现
/** * 游戏人物抽象类 */ public abstract class Person { List<Clothes> decorateClothes; public Person(List<Clothes> decorateClothes){ this.decorateClothes = decorateClothes; } //人物特性 public abstract void specialDes(); //装饰描述 public void showClothes(){ for (int i = 0; i < decorateClothes.size(); i++) { decorateClothes.get(i).clothesDes(); decorateClothes.get(i).clothesEffect(); } } }
/** * 男性角色 */ public class Men extends Person { public Men(List<Clothes> decorateClothes) { super(decorateClothes); } @Override public void specialDes() { System.out.println("这是一个强壮的男性角色,自带100点体力,50点魅力"); } }
/** * 女性角色 */ public class Women extends Person { public Women(List<Clothes> decorateClothes) { super(decorateClothes); } @Override public void specialDes() { System.out.println("这是一个柔弱的女性角色,自带100点魅力,50点体力"); } }
/** * 服饰接口 */ public interface Clothes { //表现 void clothesDes(); //效果 void clothesEffect(); }
/** * 耳环服饰 */ public class Earrings implements Clothes{ @Override public void clothesDes() { System.out.println("这是一对金闪闪的耳环"); } @Override public void clothesEffect() { System.out.println("这对耳环可以增加十点智力和30点魅力"); } }
/** * 夹克服饰 */ public class Jacket implements Clothes { @Override public void clothesDes() { System.out.println("这是一件酷酷的夹克衫"); } @Override public void clothesEffect() { System.out.println("这件夹克增加了10点体力和10点魅力"); } }
/** * 鞋子服饰 */ public class Shoes implements Clothes { @Override public void clothesDes() { System.out.println("这是一双平淡无奇的鞋子"); } @Override public void clothesEffect() { System.out.println("这双鞋子增加了5点移动速度和10点魅力"); } }
/** * 测试类 */ public class Test { public static void main(String[] args) { //初始化服饰 Clothes earrings = new Earrings(); Clothes jacket = new Jacket(); Clothes shoes = new Shoes(); List<Clothes> list1 = new ArrayList<>(); List<Clothes> list2 = new ArrayList<>(); list1.add(shoes); list1.add(jacket); list2.add(shoes); list2.add(earrings); //男人 Person men = new Men(list1); //女人 Person women = new Women(list2); men.specialDes(); men.showClothes(); women.specialDes(); women.showClothes(); } }
适用场景
1.如果一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性,避免在两个层次之间建立静态的继承联系,通过桥接模式可以使它们在抽象层建立一个关联关系。
2.抽象化角色和实现化角色可以以继承的方式独立扩展而互不影响,在程序运行时可以动态将一个抽象化子类的对象和一个实现化子类的对象进行组合,即系统需要对抽象化角色和实现化角色进行动态耦合。
3.一个类存在两个独立变化的维度,且这两个维度都需要进行扩展。
4.虽然在系统中使用继承是没有问题的,但是由于抽象化角色和具体化角色需要独立变化,设计要求需要独立管理这两者。
5.对于那些不希望使用继承或因为多层次继承导致系统类的个数急剧增加的系统,桥接模式尤为适用。
桥接模式的优点
1.分离抽象接口及其实现部分。
2.桥接模式有时类似于多继承方案,但是多继承方案违背了类的单一职责原则(即一个类只有一个变化的原因),复用性比较差,而且多继承结构中类的个数非常庞大,桥接模式是比多继承方案更好的解决方法。
3.桥接模式提高了系统的可扩充性,在两个变化维度中任意扩展一个维度,都不需要修改原有系统。
4.实现细节对客户透明,可以对用户隐藏实现细节。
桥接模式的缺点
1.桥接模式的引入会增加系统的理解与设计难度,由于聚合关联关系建立在抽象层,要求开发者针对抽象进行设计与编程。 - 桥接模式要求正确识别出系统中两个独立变化的维度,因此其使用范围具有一定的局限性。