装饰者模式
装饰者模式,为原对象增加功能时使用,装饰者模式是针对接口实现的,下面是装饰者模式的结构图。
针对Compoment这个接口进行实现,ClassA跟Decorator都实现Compoment这个接口,确保覆写func()方法,装饰者本身是不提供功能的,它只是对原有功能的追加,所以装饰者必须要持有原有的对象,也就是持有Compoment的具体实现,这里ClassA就是具体实现。
上图看到Decorator有一个Compoment类型的字段,装饰者本身也实现了Compoment,也就是说装饰者也可以对装饰者进行修饰,但无论外层包含多少层装饰者,它都必须拥有一个具体的实现。
当用户调用Compoment对象的func()方法时,想在原有功能上添加一些额外功能,就可以使用到装饰者模式。
遵循"修改封闭,扩展开放"原则,不对原有对象进行修改,我们可以实现一个Compoment的装饰对象,把原对象传入装饰器,这样就可以在不改变原代码的功能下扩展功能。
下面是代码:
public interface Compoment {
void func();
}
public class ClassA implements Component{
@Override
public void func() {
System.out.println("A");
}
}
public class Decorator implements Component {
Component component;
public Decorator(Component component){
this.component = component;
}
@Override
public void func() {
System.out.println("decorate before");
component.func();
System.out.println("decorate after");
}
}
public class Main {
public static void main(String[] args) {
ClassA classA = new ClassA();
Decorator decorator = new Decorator(classA);
decorator.func();
}
}
适配器模式
适配器模式,把当前对象进行转换,使它可以适配其他对象,下面是适配器模式的结构图。
看了上面这个图,你会发觉它跟装饰者模式的结构图一模一样,这不就是装饰者模式的结构吗?!大部分确实跟装饰者一模一样,但是仔细观察会发现,Adapter里面所持有的具体实现是Adaptee,它不存在我们上面的结构图中,也就是说它是一个"外来的对象",外来的对象本身并没有func()这个方法,我们要做的就是通过Adapter把它进行装换,使它也可以使用func()这个方法,当然实际调用使用的是Adapter来调用func()方法。不对原有对象进行修改,但是可以进行扩展,正符合"修改封闭,扩展开放"原则。
下面是代码:
public class Adaptee {
public void specFunc(){
System.out.print("func");
}
}
public interface Compoment {
void func();
}
public class ClassB implements Compoment{
@Override
public void func() {
System.out.println("func B");
}
}
public class Adapter implements Compoment{
Adaptee adaptee;
public Adapter(Adaptee adaptee){
this.adaptee = adaptee;
}
@Override
public void func() {
adaptee.specFunc();
System.out.println(" B");
}
}
public class Main {
public static void main(String[] args) {
ClassB classB = new ClassB();
classB.func();
Adaptee adaptee = new Adaptee();
Adapter adapter = new Adapter(adaptee);
adapter.func();
}
}