In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail the example analysis of the command pattern in the Java design pattern. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.
Introduction of command mode
Command mode is the encapsulation of commands. Command mode separates the responsibility of issuing orders from the responsibility of executing orders and delegates them to different objects.
Each command is an operation: the requesting party sends a request to perform an operation; the receiving party receives the request and performs the operation. The command mode allows the requesting party to be independent from the receiving party, so that the requesting party does not need to know the interface of the party receiving the request, let alone how the request was received, and whether and when the operation was executed. And how.
Role
Client (Client) role: create a specific command (ConcreteCommand) object and determine its recipient.
Command role: declares an abstract interface for all concrete command classes.
ConcreteCommand role: defines a weak coupling between the receiver and the behavior; implements the execute () method, which is responsible for invoking the corresponding operation of the receiver. The execute () method is often called an execution method.
Invoker role: responsible for invoking the command object to execute the request, the related method is called the action method.
Receiver role: responsible for the specific implementation and execution of a request. Any class can be the recipient, and the method of implementing and executing the request is called the action method.
Order case
Code demonstration
Encapsulate the request for a guest order as a request object, that is, the order class
/ / encapsulate the guest order request as a request class / order class public class Order {/ / which table order private Integer diningTable; / / the dishes ordered by the current table guest private Map FoodDic=new HashMap (); public Integer getDiningTable () {return diningTable;} public void setDiningTable (Integer diningTable) {this.diningTable = diningTable;} public Map getFoodDic () {return FoodDic } public void setFoodDic (String foodName,Integer num) {FoodDic.put (foodName,num);}}
Abstract command class
/ / Abstract command class public abstract class Command {/ / Abstract method public abstract void execute ();}
Specific command class-order command
/ / specific order command public class OrderCommand extends Command {/ / hold recipient object and order object private SeniorChef chef; private Order order; / / assign the attribute OrderCommand (SeniorChef seniorChef,Order order) {this.chef=seniorChef; this.order=order through the constructor } / / execute the specific logical behavior of the command @ Override public void execute () {System.out.println (order.getDiningTable () + "order for table") by calling the method of the recipient object; / / traverse the collection: key-- > foodName value--- > food ordered several order.getFoodDic (). ForEach ((key,value)-> {chef.makeFood (key,value)) );}}
Recipient
/ / Chef public class SeniorChef {/ / make food public void makeFood (String name,Integer num) {System.out.println ("make" + name+ "" + num+ ");}}
Requestor
/ / server class-public class Waitor {/ / the person who sends the request (command) may have multiple List commadns= Lists.newArrayList (); / / put the command into the collection public void setCmd (Command cmd) {commadns.add (cmd);} / / initiate the command function public void OrderUp () {System.out.println ("the order is coming.") / / iterate through the List collection commadns.forEach (cmd- > {if (cmdentries null null) / / execute cmd.execute () if the command is valid;});}}
Client
/ / create order object-the request is packaged as a class Order order=new Order (); order.setDiningTable (1); order.setFoodDic ("chicken leg", 2); / / create chef object-receiver SeniorChef chef=new SeniorChef (); / / create command class-combine recipient and specific request Command command=new OrderCommand (chef,order) / / create a server-caller Waitor waitor=new Waitor (); / / combine commands into waitor.setCmd (command); / / execute command waitor.OrderUp ()
Advantages of command mode
The command allows the requesting party and the receiving party to evolve independently, thus having the following advantages:
(1) Command mode makes it easy for new commands to be added to the system.
(2) the party who is allowed to receive the request decides whether to reject the request.
(3) it is easy to design a command queue.
(4) it is easy to undo and restore the request = = > can be implemented in combination with memo mode
(5) commands can be logged more easily if necessary.
The following is a schematic system to illustrate the structure of command mode.
The original intention of the command mode is to decouple the command requestor (Invoker) and the command implementer (Receiver) to facilitate all kinds of command control.
Applicable scenario
The sender and executor of a command have different lifecycles. The command was sent and not executed immediately.
Commands require a variety of administrative logic.
Need to support undo / redo operation (you can search the code for this situation on the Internet, there are a lot of them, and we won't interpret them in detail here).
Sample code
Recipient role class
Public class Receiver {/ * actually execute the corresponding action of the command * / public void action () {System.out.println ("execute the action");}}
Abstract command role class
Public interface Command {/ * execution method * / void execute ();}
Specific command role class
Public class ConcreteCommand implements Command {/ / holds the corresponding recipient object private Receiver receiver = null; / * Constructor * / public ConcreteCommand (Receiver receiver) {this.receiver = receiver;} @ Override public void execute () {/ / usually transfers the corresponding method of the recipient object to allow the receiver to actually perform the function receiver.action ();}}
Requestor role class
Public class Invoker {/ * holds command object * / private Command command = null; / * Constructor * / public Invoker (Command command) {this.command = command;} / * Action method * / public void action () {command.execute ();}}
Client role class
Public class Client {public static void main (String [] args) {/ / create the recipient Receiver receiver = new Receiver (); / / create the command object and set its receiver Command command = new ConcreteCommand (receiver); / / create the requestor and set the command object into Invoker invoker = new Invoker (command); / / execute the method invoker.action ();}}
Through a command command class, the receiver and executor are decoupled.
Apply macro commands-execute a set of commands
To put it simply, the so-called macro command is a command that contains multiple commands, which is a combination of commands.
Sample code
The system needs an interface that represents macro commands to define the interfaces needed for specific macro commands.
The management method of public interface MacroCommand extends Command {/ * macro command aggregation * can add a member command * / public void add (Command cmd); / * macro command aggregation management method * can delete a member command * / public void remove (Command cmd);}
The specific macro command MacroAudioCommand class is responsible for synthesizing individual commands into macro commands.
Public class MacroAudioCommand implements MacroCommand {private List commandList = new ArrayList (); / * Macro Command aggregation Management method * / @ Override public void add (Command cmd) {commandList.add (cmd);} / * Macro Command aggregation Management method * / @ Override public void remove (Command cmd) {commandList.remove (cmd) } / * execution method * / @ Override public void execute () {for (Command cmd: commandList) {cmd.execute ();}
Client class
Public class Julia {public static void main (String [] args) {/ / create recipient object AudioPlayer audioPlayer = new AudioPlayer (); / / create command object Command playCommand = new PlayCommand (audioPlayer); Command rewindCommand = new RewindCommand (audioPlayer); Command stopCommand = new StopCommand (audioPlayer); MacroCommand marco = new MacroAudioCommand (); marco.add (playCommand); marco.add (rewindCommand) Marco.add (stopCommand); marco.execute ();}} Summary
Looser coupling
The command mode completely decouples the object that initiates the command-- the client, and the object that implements the command-- the receiver object, that is to say, the object that initiates the command has no idea who the specific implementation object is or how to implement it.
More dynamic control
The command mode encapsulates the request, which can be parameterized, queued and logged dynamically, thus making the system more flexible.
A natural compound command
The command objects in the command mode can be easily combined into compound commands, that is, macro commands, which makes the system operation easier and more powerful.
Better scalability
Because the object that initiates the command is completely decoupled from the concrete implementation, it is easy to extend the new command, only need to implement the new command object, and then set the specific implementation object to the command object when assembling. Then you can use this command object, and the existing implementation does not need to change at all.
JDK source code parsing Runable is a typical command mode. Runnable plays the role of command, Thread acts as the caller, and the start method is its execution method / / command interface (abstract command role) public interface Runnable {public abstract void run ();} / the caller public class Thread implements Runnable {private Runnable target; public synchronized void start () {if (threadStatus! = 0) throw new IllegalThreadStateException () Group.add (this); boolean started = false; try {start0 (); started = true;} finally {try {if (! started) {group.threadStartFailed (this) }} catch (Throwable ignore) {} private native void start0 ();}
A native method, start0 (), is called to call the system method to start a thread.
The receiver is open to programmers, and you can define the receiver yourself.
/ * jdk Runnable command mode * TurnOffThread: belongs to specific * / public class TurnOffThread implements Runnable {private Receiver receiver; public TurnOffThread (Receiver receiver) {this.receiver = receiver;} public void run () {receiver.turnOFF ();} * Test class * / public class Demo {public static void main (String [] args) {Receiver receiver = new Receiver () TurnOffThread turnOffThread = new TurnOffThread (receiver); Thread thread = new Thread (turnOffThread); thread.start ();}} this is the end of the article on "sample analysis of command patterns in Java design patterns". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.