该模式属于行为型模式,行为被包装在对象里面。
复制代码
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());
}
}
复制代码