一个好的营销型网站模板,同城新闻app有哪些,seo搜索引擎优化营销案例,免费ppt模板下载手机定义
桥接模式#xff08;Bridge Pattern#xff09;是一种结构型设计模式#xff0c;它通过将抽象部分与实现部分分离#xff0c;使它们都可以独立地变化。桥接模式的关键在于将类的抽象部分与其实现部分解耦#xff0c;以便两者可以独立地变化。这种设计模式的一个主要…定义
桥接模式Bridge Pattern是一种结构型设计模式它通过将抽象部分与实现部分分离使它们都可以独立地变化。桥接模式的关键在于将类的抽象部分与其实现部分解耦以便两者可以独立地变化。这种设计模式的一个主要用途是避免类层次结构的指数增长尤其是在有多维度变化时例如设备种类与设备操作。
UML图 角色说明
Abstraction抽象类提供客户端调用的接口内部包含一个对实现部分对象Implementor的引用。RefinedAbstraction扩展抽象类扩展了Abstraction的功能通过调用Implementor来实现具体操作。Implementor实现接口定义实现部分的接口它不一定与Abstraction的接口完全一致一般是独立的。ConcreteImplementor具体实现类实现具体的功能逻辑它是实现部分的具体实现。
代码
// 实现接口
interface Implementor {void operationImpl();
}// 具体实现类A
class ConcreteImplementorA implements Implementor {Overridepublic void operationImpl() {System.out.println(ConcreteImplementorAs implementation.);}
}// 具体实现类B
class ConcreteImplementorB implements Implementor {Overridepublic void operationImpl() {System.out.println(ConcreteImplementorBs implementation.);}
}// 抽象类
abstract class Abstraction {protected Implementor implementor;public Abstraction(Implementor implementor) {this.implementor implementor;}public abstract void operation();
}// 扩展抽象类
class RefinedAbstraction extends Abstraction {public RefinedAbstraction(Implementor implementor) {super(implementor);}Overridepublic void operation() {System.out.print(RefinedAbstraction is calling: );implementor.operationImpl();}
}// 客户端代码
public class BridgePatternDemo {public static void main(String[] args) {Implementor implA new ConcreteImplementorA();Abstraction abstractionA new RefinedAbstraction(implA);abstractionA.operation();Implementor implB new ConcreteImplementorB();Abstraction abstractionB new RefinedAbstraction(implB);abstractionB.operation();}
}
适用场景
当系统需要在多个维度上进行扩展而又不希望产生大量的子类时。例如设备种类手机、电脑等和设备操作开机、关机、重启等是两个独立的维度可以使用桥接模式来分别处理。当一个类需要在不同的环境下工作且这些环境可能随时变化。 需要动态地切换实现时桥接模式可以提供灵活性因为实现和抽象可以独立变化。
总结
桥接模式通过将抽象与实现解耦提供了一种灵活扩展和维护系统的方式尤其适用于系统可能在多个维度上扩展的场景。