DEV Community

Klee Thomas
Klee Thomas

Posted on • Originally published at blog.kleeut.com

Command Object Pattern

How would I explain Command Object Pattern to Myself.

What is it?

The Command Object Pattern to encapsulate what would have otherwise been a function call inside an object that is abstracted away behind an interface.

The Command Object Pattern is a pattern of four classes:

The Command

Implements the Command Interface and takes a dependency on the receiver. The command encapsulates everything needed to call the receiver.

The Receiver

The class being on by invoking the command.

The Invoker

Depends on an abstract Command interface. Does not know anything about the concrete implementation of the Command.

The Client

High level class responsible for connecting the invoker with commands.

Why is it good?

The Command Object Pattern facilitates using the Open Closed Principle on the Invoker. Making the Invoker open for extension and closed for modification by providing behaviour at run time. This allows for independent testing of components and component reuse.

Where would you use it ?

The Command Object Pattern's use case is any where that you have an object that needs to share some behaviour across multiple instances (possibly in multiple applications) while allowing other behaviours to be specific to an instance.

An example is implementing a Button class. The button knows about display and interaction logic. The behaviour that is invoked when the button is pressed is not an implementation detail of the Button class but is provided at run time.

N.B.

This is a pattern that I thought I understood. I actually had it confused with the Command Bus / Command Handler Pattern.

Top comments (0)