官术网_书友最值得收藏!

Applicability and examples

The applicability and examples of the command pattern are as follows:

  • Undo/redo operations: The command pattern allows us to store the command object in a queue. This way, we can implement undo and redo operations.
  • Composite commands: Complex commands can be composed of simple commands using the composite pattern, and are run in a sequential order. In this way, we can build macros in an object-oriented-design manner.
  • The asynchronous method invocation: The command pattern is used in multithreading applications. Command objects can be executed in the background in separate threads. The java.lang.Runnable is a command interface.

In the following code, the runnable interface acts as a command interface, and is implemented by RunnableThread:

class RunnableThread implements Runnable
{
public void run()
{
// the command implementation code
}
}

The client invokes the command to start a new thread:

public class ClientThread 
{
public static void main(String a[])
{
RunnableThread mrt = new RunnableThread();
Thread t = new Thread(mrt);
t.start();
}
}
主站蜘蛛池模板: 锦州市| 永丰县| 文登市| 安平县| 宁德市| 邵阳市| 淮阳县| 九龙县| 北碚区| 汕头市| 普陀区| 晋宁县| 永泰县| 泽州县| 盐津县| 芷江| 长乐市| 黔江区| 基隆市| 雅安市| 阿合奇县| 龙江县| 界首市| 安龙县| 永安市| 剑河县| 绿春县| 德州市| 玉树县| 万年县| 怀来县| 永吉县| 东阳市| 西乌珠穆沁旗| 曲麻莱县| 新乐市| 偏关县| 南和县| 稷山县| 江口县| 民勤县|