В чем преимущество использования шаблона команды по сравнению с прямым назначением действий кнопкам?Позвольте мне продемонстрировать это на следующем примере.
Код: Выделить всё
// receiver
class Document {
public void save() {}
public void open() {}
}
interface Command{
void execute();
}
// Concrete Commands
class SaveCommand implements Command {
private Document document;
public SaveCommand(Document document) {
this.document = document;
}
@Override
public void execute() {
document.save();
}
}
class OpenCommand implements Command {
private Document document;
public OpenCommand(Document document) {
this.document = document;
}
@Override
public void execute() {
document.open();
}
}
// Invoker: Generic Button
class Button {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void execute() {
command.execute();
}
}
// Client Code
public class Main{
public static void main(String[] args) {
// Receiver: Document
Document document = new Document();
// Commands
Command saveCommand = new SaveCommand(document);
Command openCommand = new OpenCommand(document);
// Buttons (Invokers)
Button saveButton = new Button(saveCommand);
Button openButton = new Button(openCommand );
saveButton.execute();
openButton.execute();
}
}
Код: Выделить всё
class Document {
public void save() {}
public void open() {}
}
interface Button {
public void execute();
}
class SaveButton implements Button{
private Document document;
public SaveButton (Document document) {
this.document = document;
}
@Override
public void execute() {
document.save();
}
}
class OpenButton implements Button{
private Document document;
public OpenButton (Document document) {
this.document = document;
}
@Override
public void execute() {
document.open();
}
}
// Client Code
public class Main{
public static void main(String[] args) {
// Receiver: Document
Document document = new Document();
// Buttons (Invokers)
Button saveButton = new SaveButton(document);
Button openButton = new OpenButton(document);
saveButton.execute();
openButton.execute();
}
}
Какова польза от этого в коде, а не только в теории?
Какова польза от этого в коде, а не только в теории?
Какова польза от этого в коде, а не только в теории?
Какая польза от этого в коде? п>
Подробнее здесь: https://stackoverflow.com/questions/793 ... on-binding
Мобильная версия