您的位置:首页 > 编程语言 > Java开发

java行为设计模式——命令模式

2017-11-16 18:34 676 查看
1、模式理解:简单点可以这么说,命令由谁发送,命令由谁执行,由哪些命令

2、运用场景:命令可以同时进行,适用于并发

3、代码示例:可以参考:https://www.cnblogs.com/java-my-life/archive/2012/06/01/2526972.html

//先创建命令的接受者,孩子接收吃饭或者睡觉的命令
public class Children {

void eat(){
System.out.println("吃饭");
}
void sleep(){
System.out.println("睡觉");
}
}
//创建命令接口和具体的命令类
public interface Command {
void execute();
}

public class EatCommand implements Command{
    private Children children;
    
    public EatCommand(Children children) {
        this.children=children;
    }

    @Override
    public void execute() {
        children.eat();
    }
}

public class SleepCommand implements Command{
    private Children children;
    
    public SleepCommand(Children children) {
        this.children=children;
    }

    @Override
    public void execute() {
        children.sleep();
    }
}
//接着创建命令的发送者,妈妈发送具体命令,具体命令被接收者接收并执行
public class Mother {

private Command command;

public Mother(Command command) {
this.command=command;
}

public void action(){
command.execute();
}
}
//最后写个测试类,先创建接收者,再创建命令,最后创建发送者,由发送者实现发送命令方法
public class Main {

public static void main(String[] args) {
Children children=new Children();
Command eatCommand=new EatCommand(children);
Mother mother=new Mother(eatCommand);
mother.action();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: