裝飾模式就是給一個對象增加一些新的功能,而且是動態的,要求裝飾對象和被裝飾對象實現同一個接口,裝飾對象持有被裝飾對象的實例,關係圖如下:
(圖片來自網絡)
下面我們來看源碼:
共同的接口:
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();
}
}
自我總結:
在最開始編寫的時候,總是得不到想要的結果,最後發現在構造函數中使用的不是接口,而是具體類,導致當前方法總是會覆蓋掉之前的方法,再次,需要注意這點。