zoukankan      html  css  js  c++  java
  • Java设计模式(20)——行为模式之命令模式(Command)

    一、概述

      概念

      

       

      类似C中的callback!

      UML简图

      

      角色

      客户端:创建具体命令,指定接收者

      命令接口:声明命令的接口

      具体命令:定义接收者和行为之间的弱耦合(execute执行方法)

      请求者(Invoker):负责调用命令执行请求

      接收者:具体实施和执行请求

      举个《Java与模式》中的栗子:

      

      

    二、实践

      给出角色的示例性代码

      命令接口

    /**
     * 命令接口
     *
     * @author Administrator
     **/
    public interface Command {
        void execute();
    }

      具体命令

    /**
     * 具体命令
     *
     * @author Administrator
     **/
    public class ConcreteCommand implements Command{
        private Receiver receiver;
    
        public ConcreteCommand(Receiver receiver) {
            this.receiver = receiver;
        }
    
        @Override
        public void execute() {
            receiver.action();
        }
    }

      请求者

    /**
     * 请求者
     *
     * @author Administrator
     **/
    public class Invoker {
        private Command command;
    
        public Invoker(Command command) {
            this.command = command;
        }
        public void action() {
            command.execute();
        }
    }

      接收者

    /**
     * 接收者
     *
     * @author Administrator
     **/
    public class Receiver {
        public void action() {
            // 示例性的行动代码
            System.out.println("接收者行动#action()");
        }
    }

      示意性客户端

    /**
     * 客户端
     * @author  Administrator
     **/
    public class Client {
        public static void main(String[] args) {
            Receiver receiver = new Receiver();
            Command command = new ConcreteCommand(receiver);
            Invoker invoker = new Invoker(command);
            invoker.action();
        }
    }

    // 输出接收者行动

  • 相关阅读:
    数据结构最小生成树两个算法
    hdu-1742Ellipse(自适应辛普森)
    hdu1251统计难题
    codeforces-551C GukiZ hates Boxes
    CodeForces
    codeforces-894C Marco and GCD Sequence
    codeforces-892B Wrath
    codeforces-894B Ralph And His Magic Field
    CodeForces
    CodeForces
  • 原文地址:https://www.cnblogs.com/jiangbei/p/7766737.html
Copyright © 2011-2022 走看看