桥接模式:将抽象部分与它的实现部分分离,使它们都可以独立地变化
手机品牌与软件之间的联系
package 设计模式;
public class Text {
public static void main(String[] args) {
HandsetBrand ab;
ab=new HandsetBrandN();
ab.SetHandsetSoft(new HandsetGame());
ab.Run();
ab.SetHandsetSoft(new AddressList());
ab.Run();
ab=new HandsetBrandM();
ab.SetHandsetSoft(new HandsetGame());
ab.Run();
ab.SetHandsetSoft(new AddressList());
ab.Run();
ab.SetHandsetSoft(new Mp3());
}
}
//手机软件
abstract class HandsetSoft
{
public abstract void Run();
}
//手机品牌
abstract class HandsetBrand
{
protected HandsetSoft soft;
public void SetHandsetSoft(HandsetSoft soft)
{
this.soft=soft;
}
public abstract void Run();
}
class HandsetBrandM extends HandsetBrand
{
public void Run()
{
System.out.println("M Brand");
soft.Run();
}
}
class HandsetBrandN extends HandsetBrand
{
public void Run()
{
System.out.println("N Brand");
soft.Run();
}
}
class HandsetGame extends HandsetSoft
{
public void Run()
{
System.out.println("运行手机游戏");
}
}
class AddressList extends HandsetSoft
{
public void Run()
{
System.out.println("运行手机通讯录");
}
}
class Mp3 extends HandsetSoft
{
public void Run()
{
System.out.println("运行手机MP3");
}
}
基本代码实现
package 设计模式;
public class Text {
public static void main(String[] args) {
Abstraction ab=new RefinedAbstraction();
ab.SetImplementor(new ConcreteImplementorA());
ab.Operation();
ab.SetImplementor(new ConcreteImplementorB());
ab.Operation();
}
}
abstract class Implementor
{
public abstract void Operation();
}
class ConcreteImplementorA extends Implementor
{
public void Operation()
{
System.out.println("具体实现A的方法执行");
}
}
class ConcreteImplementorB extends Implementor
{
public void Operation()
{
System.out.println("具体实现B的方法执行");
}
}
class Abstraction
{
protected Implementor implementor;
public void SetImplementor(Implementor implementor)
{
this.implementor=implementor;
}
public void Operation()
{
implementor.Operation();
}
}
class RefinedAbstraction extends Abstraction
{
public void Operation()
{
implementor.Operation();
}
}
说明
- 桥接模式就是将抽象部分与它的实现部分分离,即实现系统可能有多角度分类,每一种分类都有可能变化,那么就把这种多角度分离出来让他们独立变化,减少它们之间的耦合
- 桥接模式中的桥接是单向的,即只能是抽象部分的对象去使用具体实现部分的对象,而不能反过来
- 使用桥接模式和原始解决方案的根本区别是通过继承还是通过合成/聚合方式去实现一个功能需求