装饰器模式:
这种模式的用作在于加工本质,对本质进行一些“美化”。就像给咖啡加上牛奶,糖球,泡沫,巧克力一般。一般情况下会使用带有顶级父类的参数构造器来进行对顶级父类加工。要谨记一件事情就是他只能明显工作于最后一层。他是对于java中实现混型的一种手法。相对于接口组合实现混型来说这种实现方式使用代码量更加少。
下面是实现的代码:
public class B { public static void main(String[] args) { TimeStamped t=new TimeStamped(new Basices()); TimeStamped t2=new TimeStamped(new SerialNumbered(new Basices())); TimeStamped t3=new TimeStamped(new TimeStamped(new Basices())); SerialNumbered s=new SerialNumbered(new Basices()); SerialNumbered s2=new SerialNumbered(new TimeStamped(new Basices())); SerialNumbered s3=new SerialNumbered(new SerialNumbered(new Basices())); } } class Basices { private String value; public String getValue() { return value; } public void setValue(String value) { this.value = value; } } class Decorator extends Basices{ protected Basices basic; public Decorator(Basices Basices){ this.basic=Basices; } public String getValue() { return basic.getValue(); } public void setValue(String value) { basic.setValue(value); } } class TimeStamped extends Decorator{ private final long timeStamp; public TimeStamped(Basices Basices) { super(Basices); timeStamp=new Date().getTime(); // TODO Auto-generated constructor stub } public long getTimeStamp() { return timeStamp; } } class SerialNumbered extends Decorator{ private static long counter=1; private final long SerialNumber=counter++; public SerialNumbered(Basices Basices) { super(Basices); // TODO Auto-generated constructor stub } public long getSerialNumber() { return SerialNumber; } }