这个是我最喜欢的用的设计模式,它的核心就是代码复用,需求要实现功能要在之前的基础的加一些其它功能,但之前接口还要保持着可用。使用场景就是这样
public class TestDecorator {
public static void main(String[] args) {
Work squarePeg = new SquarePeg();
Work decorator = new Decorator(squarePeg);
decorator.insert();
}
}
interface Work {
public void insert();
}
class SquarePeg implements Work {
public void insert() {
System.out.println("方形桩插入");
}
}
class Decorator implements Work {
private Work work;
//额外增加的功能被打包在这个List中
private ArrayList others = new ArrayList();
//在构造器中使用组合new方式,引入Work对象;
public Decorator(Work work) {
this.work = work;
others.add("挖坑");
others.add("钉木板");
}
public void insert() {
newMethod();
}
//在新方法中,我们在insert之前增加其他方法,这里次序先后是用户灵活指定的
public void newMethod() {
otherMethod();
work.insert();
}
public void otherMethod() {
ListIterator listIterator = others.listIterator();
while (listIterator.hasNext()) {
System.out.println(((String) (listIterator.next())) + " 正在进行");
}
}
}