Command mode: This design mode is more like an application of interface programming, such as clothing for children, but different clothes have different clothes, pants, shirts, and shoes, t-shirts are different, but the children do not know how to wear them. They only know what they want to wear. What should they do? The children will ask his mother to help them wear them. Here, "let mom help" is shown ", just give Mom a command (although not very appropriate --!), For children, they don't care about how to wear it. Anyway, we only need to let our mother wear it, so we only need to define an interface for wearing it.
public interface Wear(){ public void excute();}
There are many ways to carry this dress, such as shoes, shirts, and pants.
Public class wearshoe implements wear {public void excute (){..... // shoes wear action} public class wearshirt implements wear {public void excute (){..... // shirt wear action} public class wearpants implements wear {public void excute (){..... // trousers action }}
For mom, you only need to know what the children should wear and help them:
public class Mom{ Wear wear; public setCommand(Wear wear) { this.wear = wear; } public void Do() { wear.excute(); }}
What a child wants to do is to tell his mother what I want to wear and let her wear it. How can she wear it?
public class Child{ public static void main() { Mom mom=new Mom(); WearShoe wearShoe=new WearShoe(); WearPants wearPants=new WearPants(); mom.setCommand(wearShoe); mom.excute(); mom.setCommand(wearPants); mom.excute(); }}
Therefore, we can see that the command mode is:
Command mode: encapsulate a request as an object to parameterize other objects using different requests, queues, or logs. Command mode also supports unrecoverable operations.
The Undo operation is to add the undressing interface to the interface, which can help the children to wear clothes or take off their clothes:
public interface Wear(){ public void excute();
public void undo();}
Then implement it in the interface object.
The command mode is very effective when processing tasks in multiple threads. As long as the objects encapsulated by commands are put into the task queue, different threads get objects through the queue and directly execute the excute () of objects () method, instead of how the specific command is executed.
Design Mode-command mode