Home
Cloud
Big Data
CI
Install
Samples
Java
Ubuntu
Maven
Archive
Design Patterns
|
Command
References
Example
The
Receiver
The
Concrete Receiver
(1)
The
Concrete Receiver
(2)
The
Command
The
Concrete Command
The
Caller
A simple class to test the
Command
design pattern
References
Definition: (
source:
http://en.wikipedia.org/wiki/Command_pattern
)
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.
Class diagram: (
source:
http://en.wikipedia.org/wiki/Command_pattern
)
Example
The
Receiver
:
public interface Payment { void apply(); }
The
Concrete Receiver
(1):
public class Debit implements Payment { public void apply() { System.out.println("debit ..."); } }
The
Concrete Receiver
(2):
public class Credit implements Payment { public void apply() { System.out.println("credit ..."); } }
The
Command
:
public interface Transaction { void apply(); }
The
Concrete Command
:
public class TransactionImpl implements Transaction { private Payment payment; public TransactionImpl(final Payment payment) { this.payment = payment; } public void apply() { payment.apply(); } }
The
Caller
:
public class Operator { private Transaction transaction; public void setTransaction(final Transaction transaction) { this.transaction = transaction; } public void apply() { transaction.apply(); } }
A simple class to test the
Command
design pattern:
public class CommandPatternTest { public static void main(String[] args) { // create the payment Payment payment = new Debit(); // create the transaction Transaction transaction = new TransactionImpl(payment); // create the operator Operator operator = new Operator(); operator.setTransaction(transaction); // call methods operator.apply(); } }
© 2010-2022
mti
tek