装饰模式就是给一个对象增加一些新的功能,而且是动态的,要求装饰对象和被装饰对象实现同一个接口,装饰对象持有被装饰对象的实例,关系图如下:
(图片来自网络)
下面我们来看源码:
共同的接口:
public interface ModelMethodInterface {
void doMethod();
}
被装饰者实现接口:
public class ModelObject implements ModelMethodInterface {
@Override
public void doMethod() {
System.out.println("ModelObject....doMethod");
}
}
装饰者实现接口:
public class Decorator implements ModelMethodInterface {
private ModelMethodInterface modelMethodInterface;
Decorator(ModelMethodInterface modelMethodInterface) {
super();
this.modelMethodInterface = modelMethodInterface;
}
@Override
public void doMethod() {
modelMethodInterface.doMethod();
}
}
继承装饰者:
public class DecoratorA extends Decorator {
DecoratorA(ModelMethodInterface modelMethodInterface) {
super(modelMethodInterface);
}
@Override
public void doMethod() {
// TODO Auto-generated method stub
super.doMethod();
System.out.println("DecoratorA....doMethod");
}
}
继承装饰者:
public class DecoratorB extends Decorator {
DecoratorB(ModelMethodInterface modelMethodInterface) {
super(modelMethodInterface);
}
@Override
public void doMethod() {
super.doMethod();
System.out.println("DecoratorB....doMethod");
}
}
测试类:
public class Test {
public static void main(String[] args) {
System.out.println("=====================");
ModelMethodInterface mmif = new ModelObject();
System.out.println("this is the mmif doMethod");
mmif.doMethod();
System.out.println("=====================");
DecoratorA da = new DecoratorA(mmif);
System.out.println("this is the DecoratorA doMethod");
da.doMethod();
System.out.println("=====================");
DecoratorB db = new DecoratorB(da);
System.out.println("this is the DecoratorB doMethod");
db.doMethod();
}
}
自我总结:
在最开始编写的时候,总是得不到想要的结果,最后发现在构造函数中使用的不是接口,而是具体类,导致当前方法总是会覆盖掉之前的方法,再次,需要注意这点。