【设计模式】桥接模式

桥接模式:抽象部分与实现部分分离,使他们可以独立变化

模型图

代码

public abstract class Abstraction {
	@SuppressWarnings("unused")
	protected Implementor implementor;
	public Abstraction(Implementor implementor) {
		this.implementor=implementor;
	}
    abstract void operation();
}
public class RefinedAbstraction extends Abstraction {
    
	public RefinedAbstraction(Implementor implementor) {
		super(implementor);
	}

	@Override
	void operation() {
		implementor.operation();
	}
}
public abstract class Implementor {
  public  abstract void operation();
}
public class ConcreteImplementorA extends Implementor{
	@Override
	public void operation() {
	 System.out.println(" ConcreteImplementorA ");	
	}
}
public class ConcreteImplementorB extends Implementor {
	@Override
	public void operation() {
		System.out.println("ConcreteImplementorB");
	}
}
public class Test {
   public static void main(String[] args) {
	   Implementor implementor=new ConcreteImplementorA();
	   Abstraction abstraction=new RefinedAbstraction(implementor);
	   abstraction.operation();
   }
}

案例 

需求 有两款不同的手机A,B。为他们装配不同的两个功能功能A与功能B,怎么样让这两个功能可以独立的装配到两种不同的机型呢,这个时候我们就可以利用桥接模式

如上图所示,很是形象一座桥,有两个桥墩。

代码

public abstract class Function {
   public abstract void display();
}
public class FunctionA extends Function{
	@Override
	public void display() {
		System.out.print("FunctionA ");
	}
}
public class FunctionB extends Function {
	@Override
	public void display() {
		System.out.print("FunctionB");
	}
}
public abstract class  Phone {
   protected Function phone_a;
   protected Function phone_b;
   public Phone(Function phone_a,Function phone_b) {
	   this.phone_a=phone_a;
	   this.phone_b=phone_b;
   }
   
   public abstract void display();
}
public class PhoneA extends Phone{

	public PhoneA(Function phone_a, Function phone_b) {
		super(phone_a, phone_b);
	}

	@Override
	public void display() {
		phone_a.display();
		phone_b.display();
	}

	
}
public class PhoneB extends Phone {

	public PhoneB(Function phone_a, Function phone_b) {
		super(phone_a, phone_b);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void display() {
		phone_a.display();
		phone_b.display();
	}
}
public class TestCls {
	public static void main(String[] args) {
		Function phone_a=new FunctionA();
		Function phone_b=new FunctionB();
		Phone phoneA=new PhoneA(phone_a,phone_b);
		Phone phoneB=new PhoneB(phone_a,phone_b);
		phoneA.display();
		System.out.println();
		phoneB.display();
	}
}

总结

1  如上图所示 聚合是一种弱引用A包含B B不是A的一部分。如果没有B那么A一样可以独立存在。组合是一种强引用关系,A包含B B是A的一部分。如果没有B,那么A就不是完整的。

2 类似于策略模式而策略模式是相对于一个主题方案而言,谈多个不同的解决方案的。对于桥接模式则是针对不同的主题,不通的解决方案。或者不同的分类要独立控制各自的变化而言的。

猜你喜欢

转载自blog.csdn.net/worn_xiao/article/details/84563521