Bridge pattern
The bridge pattern is a design pattern used in software engineering that is meant to “decouple an abstraction from its implementation so that the two can vary independently”, introduced by the Gang of Four.[1] The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.
When a class varies often, the features of object-oriented programming become very useful because changes to a program’s code can be made easily with minimal prior knowledge about the program. The bridge pattern is useful when both the class and what it does vary often. The class itself can be thought of as the abstraction and what the class can do as the implementation. The bridge pattern can also be thought of as two layers of abstraction. —Wikipedia
Structure

Example
小哥哥送小姐姐礼物
礼物分为抽象的礼物和具体的礼物
抽象的礼物:Gift_、WarmGift_、WildGift_
具体的礼物:GiftImpl_、Book_、Flower_
抽象的礼物和具体的礼物分为 2 个继承体系,抽象礼物初始化时需传入具体礼物的实现类
public class Main {
public static void main(String[] args) {
new GG_().chase(new MM_());
}
}
abstract class Gift_ {
GiftImpl_ impl;
}
class WarmGift_ extends Gift_ {
public WarmGift_(GiftImpl_ impl) {
this.impl = impl;
}
}
class WildGift_ extends Gift_ {
public WildGift_(GiftImpl_ impl) {
this.impl = impl;
}
}
class GiftImpl_ {
}
class Book_ extends GiftImpl_ {
}
class Flower_ extends GiftImpl_ {
}
class GG_ {
public void chase(MM_ mm) {
Gift_ g = new WarmGift_(new Flower_());
give(mm, g);
}
public void give(MM_ mm, Gift_ g) {
System.out.println(g + "gived!");
}
}
class MM_ {
String name;
}

Summary
- 分离抽象与具体
- 用聚合方式(桥)连接抽象与具体
1744

被折叠的 条评论
为什么被折叠?



