定义一个接口:
public interface Work {
public void insert();
}
接口的实现类:
public class SquarePeg implements Work{
@Override
public void insert() {
System.out.println("SquarePeg.insert");
}
}
使用示范:
Work squarePeg = new SquarePeg();
squarePeg.insert();
另外,定义一个类,就是起到装饰者的作用:
public class Decorator implements Work{
private Work work;
public Decorator(Work work){
this.work = work;
}
@Override
public void insert() {
insert0();
work.insert();
insert1();
}
public void insert0(){
System.out.println("Decorator.insert0");
}
public void insert1(){
System.out.println("Decorator.insert1");
}
}
装饰者模式使用示范:
Work squarePeg = new SquarePeg();
//squarePeg.insert();
Work decorator = new Decorator(squarePeg);
decorator.insert();
不修改SquarePeg的insert方法的实现,写一个类(装饰者)在insert方法调用的前后,加一些方法insert0()、insert1()。