在软件系统中,某些类型由于自身的逻辑,它具有两个或多个维度的变化,那么如何应对这种“多维度的变化”,如何利用面向对象的技术来使得该类型能够轻松的沿着多个方向进行变化,而又不引入额外的复杂度,这就要使用Bridge模式。宗旨:将抽象部分与实现部分分离,使它们都可以独立的变化。
1、适用场景
解除或弱化两个强关联实体的关联关系。在一个软件系统的抽象化和实现化之间使用组合/聚合关系而不是继承关系,从而使两者可以相对独立地变化。
2、代码示例
(1)结构图
(2)代码实例
public interface TextImp {
public abstract void DrawTextImp();
}
public abstract class Text {
public abstract void DrawText(String text);
protected TextImp GetTextImp(String type) {
if(type.equals("Mac")) {
return new TextImpMac();
} else if(type.equals("Linux")) {
return new TextImpLinux();
} else {
return new TextImpMac();
}
}
}
public class TextBold extends Text {
private TextImp imp;
public TextBold(String type) {
imp = GetTextImp(type);
}
public void DrawText(String text) {
System.out.println(text);
System.out.println("The text is bold text!");
imp.DrawTextImp();
}
}
public class TextImpLinux implements TextImp {
public TextImpLinux() {
}
public void DrawTextImp() {
System.out.println("The text has a Linux style !");
}
}
public class TextImpMac implements TextImp {
public TextImpMac() {
}
public void DrawTextImp() {
System.out.println("The text has a Mac style !");
}
}
public class TextItalic extends Text {
private TextImp imp;
public TextItalic(String type) {
imp = GetTextImp(type);
}
public void DrawText(String text) {
System.out.println(text);
System.out.println("The text is italic text!");
imp.DrawTextImp();
}
}
public class Test {
public Test() {
}
public static void main(String[] args) {
Text myText = new TextBold("Mac");
myText.DrawText("=== A test String ===");
//
// myText = new TextBold("Linux");
// myText.DrawText("=== A test String ===");
//
// System.out.println("------------------------------------------");
//
// myText = new TextItalic("Mac");
// myText.DrawText("=== A test String ===");
//
// myText = new TextItalic("Linux");
// myText.DrawText("=== A test String ===");
}
}
(3)执行结果
=== A test String ===
The text is bold text!
The text has a Mac style !