14. Command mode in Javascript design mode ---- command
The command mode is one of the gof23 modes and the behavior mode.
Understanding command mode
In object-oriented programming, if… is widely used... Else ..., Or switch... Case... Such a condition selection statement is the "worst practice ". This type of code usually means there is room for refactoring.
Command mode is a powerful tool for killing conditional selection statements.
Generally, there is only one method in the command mode interface.
Methods of implementation classes have different functions, covering methods in interfaces.
The START command mode provides an interface
var ICommand = new Interface("ICommand",["execute"]);Provides an interface implementation class
The method of each implementation class is if... Else... Code in a code block.
// The following defines a boot command var poweroncommand = function(){;;implements(poweroncommand,icommand?#poweroncommand.prototype.exe cute = function () {alert (" ");};
Of course, you can also define many other commands to complete your other operations, such as shutdown,
// The following defines a shutdown command var poweroffcommand = function(){;;implements(poweroffcommand,icommand);poweroffcommand.prototype.exe cute = function () {alert ("shutdown ");};Executecommand method definition
// Define a method for executing commands. The method accepts a parameter, that is, the instance var executecommand = function (command) {command.exe cute ();} of the implementation class of the icommand interface ();};Use command mode
// Start executecommand (New poweroncommand (); // shutdown executecommand (New poweroffcommand ());
Yes, it is so simple to implement the command mode of starting and shutting down.
In fact, if you think about it carefully, all the windows operations are based on the command mode.
Of course, the command mode can also be used in other ways. It is not necessarily in the parameter callback mode.
The core idea of the command mode is to pass an instance of a specific class with a method to the user as an interface. The specific type information of the object disappears.
Call the method of this interface after obtaining this interface in the user's code.
The specific execution result depends on the Implementation class of the object provided by the command initiator. This gives the command initiator full control, while the user's Code does not care about the specific command classes and methods. It also makes the condition judgment statement redundant.
Simple? The command mode is actually so simple.
It is estimated that I am not clear enough -_-!!!