美文网首页
Command Pattern

Command Pattern

作者: 杨志聪 | 来源:发表于2024-06-11 09:31 被阅读0次

解决的问题

开发一个按钮组件,不同的按钮点击执行不同的命令。

代码

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();

UML

Command Pattern UML

相关文章

网友评论

      本文标题:Command Pattern

      本文链接:https://www.haomeiwen.com/subject/xwvwqjtx.html