I'm trying to implement Command Pattern, but it's much harder than I thought.
Main marker interfaces first:
public interface Invoker {}
public interface Receiver {}
Receiver specifiers:
public interface Printer {
void print();
}
public interface Configurer {
void configureAndPrint();
}
Command interface
public interface Command {
void execute();
}
And now implementations:
public class Client implements Invoker {
List<Command> commands = new ArrayList<Command>();
public List<Command> getCommands() {
return commands;
}
public void setCommands(List<Command> commands) {
this.commands = commands;
}
}
My first command
public class CSVConfiguratorJob implements Command {
Configurer configurer;
public CSVConfiguratorJob(Configurer configurer) {
this.configurer = configurer;
}
@Override
public void execute() {
configurer.configureAndPrint();
}
}
My second command
public class PDFReportJob implements Command {
Printer receiver;
public PDFReportJob(Printer receiver) {
this.receiver = receiver;
}
@Override
public void execute() {
receiver.print();
}
}
Receivers
public class CSVConfigurer implements Receiver, Configurer {
private int rows;
private int columns;
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getColumns() {
return columns;
}
public void setColumns(int columns) {
this.columns = columns;
}
@Override
public void configureAndPrint() {
rows = 5;
columns = 25;
System.out.println("rows " + rows + ", " + "columns " + columns);
}
}
--
public class PDFPrinter implements Receiver, Printer {
private int pages;
public PDFPrinter() {
this.pages = 100;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
@Override
public void print() {
System.out.println(pages);
}
}
And test
public class AppRunner {
public static void main(String[] args) {
/** Invoker **/
Client client = new Client();
/** Receivers **/
Printer printer = new PDFPrinter();
Configurer configurer = new CSVConfigurer();
/** Commands **/
Command configurerJob = new CSVConfiguratorJob(configurer);
Command reportJob = new PDFReportJob(printer);
/** Invoker setup **/
client.setCommands(Arrays.asList(configurerJob, reportJob));
for (Command command : client.getCommands()){
command.execute();
}
}
}
Is my code a Command Pattern or something different?
Command
. I was studying design patterns when I decided to implement this one. But I'm not sure about correctness of implementation. That's why I'm here. I need code review. – barbara Sep 6 '14 at 18:34StringListManager
accepting commands "clear" and "add(String)". Then you can extend it by "undo", or whatever. With a too complicated example, it all gets obfuscated. That said, your code doesn't look bad. – maaartinus Sep 7 '14 at 5:42