桥接模式(Bridge):将抽象部分与它的实现部分分离,使它们都可以独立地变化。(这里的实现部分是指抽象类和子类用来实现自己的对象)
类图:

代码:
publicabstractclass Abstract {
protected Implement implement;
publicvoid SetImplement(Implement impl){
this.implement=impl;
}
publicabstractvoid operation();
}
publicclass RefinedAbstraction extends Abstract{
@Override
publicvoid operation() {
if(super.implement!=null){
super.implement.operationImpl();
}
}
}
publicabstractclass Implement {
publicabstractvoid operationImpl();
}
publicclass ConcreteImplementA extends Implement {
@Override
publicvoid operationImpl() {
System.out.println("第一种实现方式");
}
}
publicclass ConcreteImplementB extends Implement {
@Override
publicvoid operationImpl() {
System.out.println("第二种实现方式");
}
}
publicstaticvoid main(String[] args) {
Abstract abs=new RefinedAbstraction();
abs.SetImplement(new ConcreteImplementA());
abs.operation();
abs.SetImplement(new ConcreteImplementB());
abs.operation();
}
好处:可以随意增加实现方式和Abstractd的子类,任意组装功能。
继承是扩展对象功能的一种常见手段,继承扩展功能是一维的,也就是变化的因素只有一种。如果出现变化因素有两种,继承是没有办法实现的。这时使用桥接可以很好的解决问题。桥接连接的是抽象部分和实现部分
本文详细解释了桥接模式的概念及其在抽象与实现分离方面的优势,通过实例展示了如何灵活组合功能,解决继承扩展限制的问题。通过具体代码实现,直观呈现了桥接模式在软件设计中的应用价值。
1476

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



