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

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();
}
}
主站蜘蛛池模板: 三原县| 灵台县| 红河县| 区。| 孟州市| 新干县| 蒲城县| 平阳县| 铁岭市| 綦江县| 中卫市| 武威市| 景洪市| 固阳县| 平原县| 华池县| 龙泉市| 松滋市| 班玛县| 于都县| 西平县| 富顺县| 米泉市| 札达县| 中阳县| 南华县| 出国| 出国| 同江市| 清丰县| 崇明县| 邵武市| 峨山| 神木县| 逊克县| 永川市| 大余县| 海晏县| 马关县| 固安县| 扶沟县|