一句话总结
多个维度
内容
桥接模式的核心是解耦抽象和具体,使两者独立变化;抽象和具体指两个独立变化的维度,其中抽象包含实现。抽象和实现共同完成同一个功能。
场景
消息按消息类型分为系统消息和邮件消息,按紧急程度分为普通消息和紧急消息。
类图
代码示例
// 抽象
public abstract class Abstraction {
protected IImplementor mImplementor;
public Abstraction(IImplementor implementor) {
this.mImplementor = implementor;
}
public void operation() {
this.mImplementor.operationImpl();
}
}
// 修正抽象
public class RefinedAbstraction extends Abstraction {
public RefinedAbstraction(IImplementor implementor) {
super(implementor);
}
@Override
public void operation() {
super.operation();
System.out.println("refined operation");
}
}
// 抽象实现
public interface IImplementor {
void operationImpl();
}
// 具体实现
public class ConcreteImplementorA implements IImplementor {
public void operationImpl() {
System.out.println("I'm ConcreteImplementor A");
}
}
// 具体实现
public class ConcreteImplementorB implements IImplementor {
public void operationImpl() {
System.out.println("I'm ConcreteImplementor B");
}
}
public class Test {
public static void main(String[] args) {
// 来一个实现化角色
IImplementor imp = new ConcreteImplementorA();
// 来一个抽象化角色,聚合实现
Abstraction abs = new RefinedAbstraction(imp);
// 执行操作
abs.operation();
}
}
源码分析
无
网友评论