Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 454d0cf

Browse files
author
deeper
committed
add commond
1 parent 2a4daaa commit 454d0cf

File tree

5 files changed

+70
-0
lines changed

5 files changed

+70
-0
lines changed
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package com.ruoxu.pattern.command;
2+
/**
3+
* 执行具体操作的命令
4+
*/
5+
public interface Command {
6+
void execute();
7+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.ruoxu.pattern.command;
2+
3+
public class ConcreteCommand implements Command{
4+
private Receiver receiver; // 持有一个对接收者对象的引用
5+
6+
public ConcreteCommand(Receiver receiver) {
7+
this.receiver = receiver;
8+
}
9+
@Override
10+
public void execute() {
11+
// 调用接收者的相关方法来执行具体逻辑
12+
receiver.action();
13+
}
14+
15+
}

‎src/com/ruoxu/pattern/command/Demo.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.ruoxu.pattern.command;
2+
/**
3+
* 命令模式(简单)
4+
* 定义:将一个请求封装成一个对象,从而让用户使用不同的请求把客户端参数化,对请求排队或者记录请求日志,以及支持可撤销的操作。
5+
*
6+
* 使用场景:需要抽象出待执行的动作,然后以参数的形式提供出来--类似于过程设计中的回调机制,而命令模式正式回调机制的一个面向对象的替代品。
7+
* 在不同的时刻指定,排列和执行请求。一个命令对象可以有与初始请求无关的生存期。
8+
* 需要支持取消操作。
9+
* 支持修改日志功能,这样当系统崩溃时,这些修改可以被重做一遍。
10+
* 需要支持事务操作。
11+
*
12+
* 总结:命令模式虽然不难,只是相对繁琐,一个简单的调用关系被解耦成多个部分,但是命令模式结构清晰。
13+
*
14+
* 注意:敏捷开发原则告诉我们,不要为代码添加基于猜测的,实际不需要的功能。如果不清楚一个系统是否需要命令模式,一般就不要急着去实现它,
15+
* 事实上,在需要的时候通过重构实现这个模式并不困难。
16+
*/
17+
public class Demo {// Client,比如说【人】
18+
public static void main(String[] args) {
19+
Receiver receiver = new Receiver();// 接收者角色,如【关机命令的底层逻辑】
20+
Command command = new ConcreteCommand(receiver);// 命令角色,如【关机命令的 执行方法,cmd命令】
21+
Invoker invoker = new Invoker(command);// 请求者角色,如【关机的按钮,这个按钮对应着Command这个命令】
22+
23+
invoker.action();
24+
}
25+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.ruoxu.pattern.command;
2+
3+
public class Invoker {
4+
private Command command;// 持有一个对相应命令对象的引用
5+
6+
public Invoker(Command command) {
7+
this.command = command;
8+
}
9+
10+
public void action(){
11+
// 调用具体命令对象的相关方法,执行具体命令
12+
command.execute();
13+
}
14+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package com.ruoxu.pattern.command;
2+
/**
3+
* 真正执行具体命令逻辑的方法
4+
*/
5+
public class Receiver {
6+
public void action(){
7+
System.out.println("执行具体操作");
8+
}
9+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /