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

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();
}
}
主站蜘蛛池模板: 阳曲县| 肥西县| 安阳市| 松滋市| 通化市| 永登县| 信阳市| 太原市| 博兴县| 勃利县| 临高县| 四平市| 都昌县| 轮台县| 郁南县| 肥乡县| 长泰县| 威信县| 镇江市| 嘉义县| 河津市| 巩义市| 云梦县| 南岸区| 三原县| 喀喇| 报价| 云浮市| 固始县| 丽水市| 青田县| 乌拉特后旗| 崇左市| 平南县| 普陀区| 宣武区| 清丰县| 喀什市| 双桥区| 饶河县| 奎屯市|