解决的问题
开发一个按钮组件,不同的按钮点击执行不同的命令。
代码
Command
:
package com.cong.designpattern.command;
public interface Command {
public void execute();
}
Button
:
package com.cong.designpattern.command;
public class Button {
private Command command;
public Button(Command command) {
this.command = command;
}
public void onClick() {
this.command.execute();
}
}
DocumentService
:
package com.cong.designpattern.command;
public class DocumentService {
public void delete() {
System.out.println("Delete document");
}
}
DeleteDocumentCommand
:
package com.cong.designpattern.command;
public class DeleteDocumentCommand implements Command{
DocumentService documentService;
public DeleteDocumentCommand(DocumentService documentService) {
this.documentService = documentService;
}
@Override
public void execute() {
this.documentService.delete();
}
}
Test code:
DocumentService documentService = new DocumentService();
DeleteDocumentCommand deleteDocumentCommand = new DeleteDocumentCommand(documentService);
Button button = new Button(deleteDocumentCommand);
button.onClick();
网友评论