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

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();
}
}
主站蜘蛛池模板: 五峰| 措勤县| 潜江市| 赞皇县| 双桥区| 济阳县| 水富县| 施秉县| 博白县| 河曲县| 邹城市| 资中县| 漳州市| 桐柏县| 汝阳县| 芦溪县| 延庆县| 信宜市| 临漳县| 平武县| 仙桃市| 庆阳市| 宣恩县| 辽阳市| 龙州县| 张家川| 奎屯市| 青神县| 阿勒泰市| 新平| 新干县| 铜川市| 盈江县| 本溪市| 曲沃县| 石林| 泾源县| 城市| 临安市| 阿拉尔市| 焦作市|