Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

java - How does the Command pattern decouple the sender from the receiver?

The Command pattern has an IReceiver interface with few methods and corresponding to each method there are concrete Command objects (implementing an interface ICommand with execute() method).

I have read that the client knows about the concrete receiver and concrete command and it is usually the client setting up the receiver object in the concrete command object. Then why it is said it decouples the sender and the receiver?

When the client already knows the concrete receiver then I feel this is not loose coupling and also the client in this case can directly call the APIs (methods) on the receiver object.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Directly from Wikipedia:

The command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time.

Edit

After re-reading the Gang of Four's section on the Command pattern, I thought up a better scenario. Let's say you have a GUI library, which defines the following:

public interface Command {
    public void execute();
}

public class Button {
    private Command command;

    public Button(Command command) {
        this.command = command;
    }

    public void click() {
        command.execute();
    }
}

The Button, in this case, is the receiver of a command, and your code, that creates actual instances of Buttons, is the client. Of course, when you create a button, you have to define some concrete implementations of the Command interface. But the GUI library does not need to know about these classes; all it needs is the interface. This is how the GUI code is decoupled from your code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...