设计模式-装饰者

之前的模板方法虽然解决了代码多余的问题,但是缺点也是显而易见的,我只能被迫接收所有继承的,所以有了这第二个模式 装饰者模式

还是之前的业务逻辑,现在我可以这么写

public interface Command(){

public void excute();

}

//一个类来执行输出日志

public class Printlog implements Command(){

Command cmd;

public Printlog(Command cmd){

this.cmd=cmd;

}

@Override

public void excute(){

//日志

....

this.cmd.excute();

}

}

//一个类用来性能统计

public class Performance implements Command(){

Command cmd;

public Performance(Command cmd){

this.cmd=cmd;

}

@Override

public void excute(){

//性能统计

.....

this.cmd.excute();

}

}

public PlaceOrderCommand implements Command(){

@Override

public void excete(){

//下单操作

}

}

psvm{

//现在想下单的时候进行性能统计和打印日志

//理一下顺序 创建Printlog 需要Performance  创建Performance需要PlaceOrderCommand

//先创建PlaceOrderCommand 传入Performance  再创建Performance传入Printlog

//先执行Printlog的excete()方法,执行完日志操作之后 调用再执行Performance中的excute()方法,执行完日志操作之后 执行其中的excute()方法。

Command cmd=new Printlog (new Performance (new PlaceOrderCommand ()));

cmd.excute()

//如果只希望打印日志不希望进行性能统计

Command cmd=new Printlog (new PlaceOrderCommand ());

cmd.excute();

}

可以使用任意数量的装饰器,还可以任意次序执行。最终的业务逻辑放在最后,如果需要先执行业务逻辑再统计数据,也只需要更改本方法中的执行顺序而已。

猜你喜欢

转载自www.cnblogs.com/Vinlen/p/12759810.html