該模式屬於行為型模式,行為被包裝在物件裡面。
複製程式碼
public interface Action {
public void perform();
}
public interface CommandAccepter {
public void save();
public void open();
public void close();
}
複製程式碼
public class Macro {
private final List<Action> actions;
public Macro(){
actions = new ArrayList<>();
}
public void record(Action action){
actions.add(action);
}
public void run(){
actions.forEach(Action::perform);
}
}
複製程式碼
public class Open implements Action {
private final CommandAccepter editor;
public Open(CommandAccepter editor){
this.editor=editor;
}
@Override
public void perform(){
editor.open();
}
}
複製程式碼
public class Demo {
public static void main(String[] args) {
Macro m=new Macro();
CommandAccepter accepter = null;
m.record(new Open(accepter));
m.record(()->accepter.close());
}
}
複製程式碼