当前位置:网站首页>Command pattern
Command pattern
2022-06-29 04:23:00 【Change with affection】
Command mode introduction
- Command mode (Command Pattern) : In software design , We often need to send requests to certain objects , But I don't know who the recipient of the request is , I don't know what the requested operation is , We just need to specify the specific request receiver when the program is running , here , You can use command mode to design
- The naming pattern enables the sender and receiver to decouple from each other , Make the calling relationship between objects more flexible , Realize decoupling
- In naming In the pattern , Will encapsulate a request as - An object , In order to use different parameters to represent different requests ( Named ), At the same time, command mode also supports revocable operations
- Easy to understand : The general gave orders , Soldiers to carry out . There are several of them : The general ( The order issuer )、 rank-and-file soldiers ( The specific executor of the order )、 command ( Connect generals and soldiers ).
Invoker It's the caller ( The general ),Receiver It's the callee ( rank-and-file soldiers ),ConcreteCommand Is the command , Realized Command Interface , Hold the receiver
The roles and responsibilities of naming patterns - Invoker It's the role of the caller
- Command: It's the command character , All the commands that need to be executed are here , It can be an interface or an abstract class
- Receiver: The role of the recipient , Know how to implement and perform a request related operation
- ConcreteCommand: Will one A recipient object is bound to an action , Call the corresponding operation of the receiver , Realization execute
Case a : Naming patterns

// Create command interface
public interface Command {
// Executive action ( operation )
public void execute();
// Undo action ( operation )
public void undo();
}
public class LightReceiver {
public void on() {
System.out.println(" The light is on .. "); }
public void off() {
System.out.println(" The lights are off .. "); }
}
public class LightOffCommand implements Command {
// polymerization LightReceiver
LightReceiver light;
// Constructors
public LightOffCommand(LightReceiver light) {
this.light = light; }
@Override
public void execute() {
// Call the receiver's method
light.off();
}
@Override
public void undo() {
// Call the receiver's method
light.on();
}
}
public class LightOnCommand implements Command {
// polymerization LightReceiver
LightReceiver light;
// Constructors
public LightOnCommand(LightReceiver light) {
this.light = light; }
@Override
public void execute() {
// Call the receiver's method
light.on();
}
@Override
public void undo() {
// Call the receiver's method
light.off();
}
}
public class RemoteController {
// open The command array of buttons
Command[] onCommands;
Command[] offCommands;
// Execute the revocation order
Command undoCommand;
// Constructors , Complete button initialization
public RemoteController() {
onCommands = new Command[5];
offCommands = new Command[5];
for (int i = 0; i < 5; i++) {
onCommands[i] = new NoCommand();
offCommands[i] = new NoCommand();
}
}
// Give our buttons the commands you need
public void setCommand(int no, Command onCommand, Command offCommand) {
onCommands[no] = onCommand;
offCommands[no] = offCommand;
}
// Press the on button
public void onButtonWasPushed(int no) {
// no 0
// Find the on button you pressed , And call the corresponding method
onCommands[no].execute();
// Record this operation , Used to revoke
undoCommand = onCommands[no];
}
// Press the on button
public void offButtonWasPushed(int no) {
// no 0
// Find the off button you pressed , And call the corresponding method
offCommands[no].execute();
// Record this operation , Used to revoke
undoCommand = offCommands[no];
}
// Press the undo button
public void undoButtonWasPushed() {
undoCommand.undo(); }
}
public class Client {
public static void main(String[] args) {
// Use command design patterns , Finish by remote control , The operation of electric lights
// Create objects for lights ( The recipient )
LightReceiver lightReceiver = new LightReceiver();
// Create light related switch commands
LightOnCommand lightOnCommand = new LightOnCommand(lightReceiver);
LightOffCommand lightOffCommand = new LightOffCommand(lightReceiver);
// Need a remote control
RemoteController remoteController = new RemoteController();
// Set up commands for our remote control , such as no = 0 It's the operation of turning on and off the lights
remoteController.setCommand(0, lightOnCommand, lightOffCommand);
System.out.println("-------- Press the light on button -----------");
remoteController.onButtonWasPushed(0);
System.out.println("-------- Press the light off button -----------");
remoteController.offButtonWasPushed(0);
System.out.println("-------- Press the undo button -----------");
remoteController.undoButtonWasPushed();
}
}
Comply with opening and closing principle , At this time, we add a TV switch
public class TVReceiver {
public void on() {
System.out.println(" The TV is on .. "); }
public void off() {
System.out.println(" The TV is off .. "); }
}
public class TVOnCommand implements Command {
// polymerization TVReceiver
TVReceiver tv;
// Constructors
public TVOnCommand(TVReceiver tv) {
this.tv = tv; }
@Override
public void execute() {
// Call the receiver's method
tv.on();
}
@Override
public void undo() {
// Call the receiver's method
tv.off();
}
}
public class TVOffCommand implements Command {
// polymerization TVReceiver
TVReceiver tv;
// Constructors
public TVOffCommand(TVReceiver tv) {
this.tv = tv; }
@Override
public void execute() {
// Call the receiver's method
tv.off();
}
@Override
public void undo() {
// Call the receiver's method
tv.on();
}
}
System.out.println("========= Use the remote control to operate the TV ==========");
TVReceiver tvReceiver = new TVReceiver();
TVOffCommand tvOffCommand = new TVOffCommand(tvReceiver);
TVOnCommand tvOnCommand = new TVOnCommand(tvReceiver);
// Set up commands for our remote control , such as no = 1 It's the TV on and off operation
remoteController.setCommand(1, tvOnCommand, tvOffCommand);
System.out.println("-------- Press the on button on the TV -----------");
remoteController.onButtonWasPushed(1);
System.out.println("-------- Press the off button on the TV -----------");
remoteController.offButtonWasPushed(1);
System.out.println("-------- Press the undo button -----------");
remoteController.undoButtonWasPushed();
The command mode is Spring frame JdbcTemplate Application source code analysis
Extract the core source code
public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
public <T> List<T> query(String sql, RowMapper<T> rowMapper) throws DataAccessException {
return (List)result(this.query((String)sql, (ResultSetExtractor)(new RowMapperResultSetExtractor(rowMapper))));
}
@Nullable
public <T> T query(final String sql, final ResultSetExtractor<T> rse) throws DataAccessException {
Assert.notNull(sql, "SQL must not be null");
Assert.notNull(rse, "ResultSetExtractor must not be null");
if (this.logger.isDebugEnabled()) {
this.logger.debug("Executing SQL query [" + sql + "]");
}
class QueryStatementCallback implements StatementCallback<T>, SqlProvider {
QueryStatementCallback() {
}
@Nullable
public T doInStatement(Statement stmt) throws SQLException {
ResultSet rs = null;
Object var3;
try {
rs = stmt.executeQuery(sql);
var3 = rse.extractData(rs);
} finally {
JdbcUtils.closeResultSet(rs);
}
return var3;
}
public String getSql() {
return sql;
}
}
return this.execute(new QueryStatementCallback(), true);
}
}
@FunctionalInterface
public interface StatementCallback<T> {
@Nullable
T doInStatement(Statement var1) throws SQLException, DataAccessException;
}
- StatementCallback Interface , Similar to the command interface (Command)
- class QueryStatementCallback implements StatementCallback, SqlProvider, Anonymous inner class , Realized The command interface , At the same time, it also acts as the command receiver
- The command caller is JdbcTemplate , among execute(StatementCallback action) In the method , call action.doInStatement Method 、 Different implementations StatementCallback Object of the interface , Corresponding to different doInStatemnt Implementation logic
- In addition, realize StatementCallback Subclasses of command interfaces include QueryStatementCallback…

Command mode summary
- Decouple the requested object from the requested object . The object of the request is the caller , The caller just calls the... Of the command object execute() Method to make the receiver work , You don't have to know who the recipient is 、 How is it realized , The command object is responsible for getting the receiver to perform the requested action , in other words :” Request originator ” and “ The executor of the request ” The decoupling is realized by command objects , Command objects act as bridges
- Easy to design , A command queue , Just put the command object in the queue , You can execute commands in multiple threads
- Easy to undo and redo requests
- Insufficient command mode : May cause some systems to have too many specific command classes , It increases the complexity of the system
- An empty command is also a design pattern , It saves us the operation of void judgment . In the example above , If there is no empty command , Every time we press a button, we have to judge empty , This brings us some trouble in coding .
- Classic application scenario of command mode : A button in the interface is a command 、 simulation CMD (DOS command ) Cancellation of order / recovery 、 Trigger feedback mechanism
边栏推荐
- [C language] explain the thread recycling function pthread_ join
- Error accessing database
- Call snapstateon closed sou from Oracle CDC
- Remote connection of raspberry pie in VNC Viewer Mode
- Ling Jing thinks about her own way
- Pytorch read / write file
- How to merge upstream and downstream SQL data records
- Open source demo| you draw and I guess -- make your life more interesting
- On June 27, 2022, I have the right to choose the journey of the summer vacation.
- 1015 德才论
猜你喜欢

Anaconda自带的Spyder编辑器启动报错问题
![[hackthebox] dancing (SMB)](/img/bb/7bf81004b9cee80ae49bb0c0c2b810.png)
[hackthebox] dancing (SMB)

Webapck system foundation

选对学校,专科也能进华为~早知道就好了

Inftnews | metauniverse technology will bring a new shopping experience

New listing of operation light 3.0 -- a sincere work of self subversion across the times
![[C language] explain the thread exit function pthread_ exit](/img/fb/96db1c712370dbb216a06440ecdc5e.png)
[C language] explain the thread exit function pthread_ exit

Developer scheme · environmental monitoring equipment (Xiaoxiong school IOT development board) connected to graffiti IOT development platform

【HackTheBox】dancing(SMB)

What are the basic usage methods of MySQL
随机推荐
How to keep database and cache consistent
【HackTheBox】dancing(SMB)
Go Foundation (I)
C language -- branch structure
NotImplementedError: Could not run torchvision::nms
I came from a major, so I didn't want to outsource
如何创建 robots.txt 文件?
人民银行印发《关于支持外贸新业态跨境人民币结算的通知》
How to merge upstream and downstream SQL data records
Ling Jing thinks about her own way
Log in to the MySQL database and view the version number on the command line
MySQL can only add small tables when adding tables dynamically. If you increase the size of tables, you won't read data when running tasks. Is there any solution
【HackTheBox】dancing(SMB)
[WC2021] 斐波那契——数论、斐波那契数列
JSX的基本使用
[new function] ambire wallet integrates Metis network
[C language] explain the thread recycling function pthread_ join
Seattention channel attention mechanism
Untitled
Anaconda自带的Spyder编辑器启动报错问题