I'm Sasaki from Media Development, Excite Japan Co., Ltd.
It's a design pattern that everyone loves, but the Lambda expression introduced from Java 8 makes it easier to apply, so I'll introduce it now.
The command pattern is written as follows. File Action interface
FileAction.java
public interface FileAction {
void openFile();
void writeFile();
void closeFile();
}
Command.java
public interface Command {
void execute();
}
OpenFile.java
public class OpenFile implements Command {
private final FileAction FileAction;
public OpenFile(FileAction fileAction) {
this.fileAction = fileAction;
}
@Override
public void execute() {
fileAction.openFile();
}
}
CloseFile.java
public class CloseFile implements Command {
private final FileAction FileAction;
public CloseFile(FileAction fileAction) {
this.fileAction = fileAction;
}
@Override
public void execute() {
fileAction.closeFile();
}
}
WriteFile.java
public class WriteFile implements Command {
private final FileAction FileAction;
public WriteFile(FileAction fileAction) {
this.fileAction = fileAction;
}
@Override
public void execute() {
fileAction.writeFile();
}
}
Macro.java
public class Macro {
private final List<Runnable> commands;
public Macro(){
this.commands = new ArrayList<>();
}
public void record(Command command) {
this.commands.add(command);
}
public void run(){
this.commands.forEach(e -> {
e.execute();
});
}
}
I only issue three commands, but I have to implement the Command
interface for each, which is quite annoying. If you partially rewrite this with Java: Lambda, it will be refreshing.
FileActionImpl.java
public class FileActionImpl implements FileAction {
@Override
public void openFile() {
System.out.println("open");
}
public void writeFile() {
System.out.println("write");
}
@Override
public void closeFile() {
System.out.println("close");
}
}
Create a class that implements the FileAction interface and collect methods there. (Here, it is only standard output for easy understanding)
Macro macro = new Macro();
FileActionImpl action = new FileActionImpl();
macro.record(() -> action.openFile());
macro.record(() -> action.writeFile());
macro.record(() -> action.closeFile());
macro.execute();
As above, write what you want the caller to do with each Lambda expression. Now, it will be executed when execute is executed.
It doesn't look like one operation and one file, so I think it's convenient when you want to save labor.
It's been 6 years since Java 8 was released. It's fast. Surprisingly, I don't see many design patterns optimized for Lambda expressions, so I wrote it.
Excite is looking for an engineer. We are looking forward to hearing from you. https://www.wantedly.com/projects/529139
Have a nice year !!
Recommended Posts