今天看到了一篇关于设计模式之装饰者模式的文章及代码,感觉写的不错,分享出来大家看看。
代码是我自己改版的,写的有些乱,别介意哈
原始接口
package org.mm.decorator;
public interface Original {
public String create();
}
原始接口实现类
package org.mm.decorator;
public class RealOriginal implements Original{
@Override
public String create() {
// TODO Auto-generated method stub
return "xiaoQ's Original !";
}
}
抽象的装饰者类(这个才是关键)
package org.mm.decorator;
public abstract class OriginalDecorator implements Original{
Original original;
public OriginalDecorator(Original o){
this.original = o;
}
}
装饰者的实现类一
package org.mm.decorator;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateOriginal extends OriginalDecorator{
public DateOriginal(Original o) {
super(o);
// TODO Auto-generated constructor stub
}
@Override
public String create() {
// TODO Auto-generated method stub
String oriString = original.create();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String date = format.format(new Date());
return oriString+"date:"+date;
}
}
装饰者的实现类二
package org.mm.decorator;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeOriginal extends OriginalDecorator{
public TimeOriginal(Original o) {
super(o);
// TODO Auto-generated constructor stub
}
@Override
public String create() {
// TODO Auto-generated method stub
String oriString = original.create();
DateFormat format = new SimpleDateFormat("HH:mm:ss");
String time = format.format(new Date());
return oriString+" time "+time;
}
}
测试类
package org.mm.decorator;
public class TestDecorator {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Original original = new TimeOriginal(new DateOriginal(new RealOriginal()));
System.err.println(original.create());
}
}
结果输出
xiaoQ's Original !date:2013-09-04 time 19:51:58
或许看了这些很多人也没什么感触,但是真正用过的人应该感觉到其内涵及真正的用处,记得看shiro的时候里面就涉及到这样
的写法。当时也不是很理解。后来代码看多了才有所感悟。