桥接模式
定义: 将抽象部分与它的实现部分分离,使它们都可以独立地变化.
/**
* 抽象类
*/
public abstract class Implementor{
public abstract void operation();
}
/**
* Implementor 派生类 ImplementorA
*/
public class ImplementorA extends Implementor{
@Override
public void operation() {
System.out.println("classA");
}
}
/**
* Implementor 派生类 ImplementorB
*/
public class ImplementorB extends Implementor{
@Override
public void operation() {
System.out.println("classB");
}
}
public abstract class Abstraction{
protected Implementor implementor;
public void setImplementor(Implementor implementor){
this.implementor = implementor;
}
public abstract void operation();
}
public class RefinedAbstraction extends Abstraction{
@Override
public void operation() {
implementor.operation();
}
}
/**
* 客户端代码
* @param args
*/
public static void main (String[] args){
Abstraction abstraction = new RefinedAbstraction();
abstraction.setImplementor(new ImplementorA());
abstraction.operation();
abstraction.setImplementor(new ImplementorB());
abstraction.operation();
}
使用状况:
1.不希望在抽象和它的实现之间有一个固定的绑定关系时.
2.类的抽象以及他的实现都应该可以通过生成子类的方法加以扩充时.
3.对一个抽象类的实现部分的修改应该对客户不产生影响时.
适配器模式
定义: 将一个类的接口转换成客户希望的另外一个接口
适用范围: 当想要使用一个已经存在的类,但是该类的接口不符合现有的要求时.
当需要创建一个可以被复用的类,该类能够与其他无关的类甚至无法预见的类协同工作时.
当需要使用一些已经存在的子类,但是不可能对所有的都进行子类化以匹配它们的接口时,对象适配器可以对其父
类接口进行适配.