定义一个接口:
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()。
本文介绍了一个简单的装饰者模式实现案例,通过定义一个接口Work及其实现类SquarePeg,展示了如何在不修改原始类的基础上增加新的行为。进一步通过装饰者类Decorator在原有方法调用前后加入额外的操作。
1146

被折叠的 条评论
为什么被折叠?



