码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式之Command模式(笔记)

时间:2015-07-01 18:31:58      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:command

命令模式:将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化,对请求排队或记录请求日志,以及支持可撤销的操作。
技术分享
首先定义一个Receiver类,用来执行请求

public class Receiver {

    public void action(){
        System.out.println("执行请求");
    }
}

接着定义Command抽象类,用来声明执行操作的接口

public abstract class Commands {

    protected Receiver receiver;

    public Commands(Receiver receiver){
        this.receiver=receiver;
    }

    public abstract void execute();
}

接着定义ConcreteCommand继承Command类

public class ConcreteCommand extends Commands{

    public ConcreteCommand(Receiver receiver) {
        super(receiver);

    }

    @Override
    public void execute() {
        receiver.action();

    }
}

然后定义Invoker类,要求该命令执行这个请求

public class Invoker {

    private Commands command;

    public void setCommand(Commands command){
        this.command=command;
    }

    public void executeCommand(){
        command.execute();
    }
}

客户端代码

public static void main(String[] args) {
    //命令模式
        Receiver receiver=new Receiver();
        Commands commands=new ConcreteCommand(receiver);
        Invoker invoker=new Invoker();
        invoker.setCommand(commands);
        invoker.executeCommand();
   }

版权声明:本文为博主原创文章,未经博主允许不得转载。

设计模式之Command模式(笔记)

标签:command

原文地址:http://blog.csdn.net/qq_16687803/article/details/46710923

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!