Although the previous template method solves the problem of redundant code, the shortcomings are also obvious, I can only be forced to accept all inherited, so with this second mode decorator
Still the previous business logic, now I can write like this
public interface Command(){
public void excute();
}
// A class to perform output logging
public class Printlog implements Command(){
Command cmd;
public Printlog(Command cmd){
this.cmd=cmd;
}
@Override
public void excute(){
// Log
....
this.cmd.excute();
}
}
// A class is used for performance statistics
public class Performance implements Command(){
Command cmd;
public Performance(Command cmd){
this.cmd=cmd;
}
@Override
public void excute(){
// Performance statistics
.....
this.cmd.excute();
}
}
public PlaceOrderCommand implements Command(){
@Override
public void excete(){
// Order operation
}
}
psvm{
// Perform performance statistics and print logs when you want to place an order now
// Order the order to create Printlog and need Performance to create Performance requires PlaceOrderCommand
// First create PlaceOrderCommand and pass in Performance, then create Performance and pass in Printlog
// Execute the excete () method of Printlog first, call and then execute the execute () method in Performance after performing the log operation, and execute the execute () method after performing the log operation.
Command cmd=new Printlog (new Performance (new PlaceOrderCommand ()));
cmd.excute()
// If you only want to print the log and do not want to perform performance statistics
Command cmd=new Printlog (new PlaceOrderCommand ());
cmd.excute();
}
Any number of decorators can be used, and they can be executed in any order. The final business logic is at the end. If you need to execute the business logic first and then count the data, you only need to change the execution order in this method.