zoukankan      html  css  js  c++  java
  • 命令模式

    命令模式的定义:
    Encapsulated a request as an object ,thereby letting you parameterize clients with different requests, queue or log requests,
    and support undoable operations.
    将一个请求封装成一个对象,从而让你使用不同的请求把客户端参数化,对请求排队或者记录请求日志,可以提供命令的撤销和恢复功能

    在类图中有三个角色:
    Receive接收者角色:该角色就是执行角色,命令传递到这里就会被执行
    Command命令角色:需要执行的所有命令都在这里声明
    Invoker调用者角色:接收到命令,并执行命令

    命令模式是把请求方(Invoker)和执行方(Receiver)分开
    //通用Receiver类
    public abstract class Receiver{
        public abstract void doSomething();
    }
    //具体Receiver类
    public class ConcreteReceiver1 extends Receiver{
        public void doSomething(){...}
    }
    
    public class ConcreteReciver2 extends Receiver{
        public void doSomething(){...}
    }
    
    //抽象Command类
    public abstract class Command{
        public abstract void execute();
    }
    //具体Command类
    public class ConcreteCommand1 extends Command{
        private Receiver receiver;
        public ConcreteCommand1(Receiver receiver){
            this.receiver=receiver;
        }
        
        public void execute(){
            this.receiver.doSomething();
        }
        
    }
    public class ConcreteCommand2 extends Command{
        private Receiver receiver;
        public ConcreteCommand2(Receiver receiver){
            this.receiver=receiver;
        }
        
        public void execute(){
            this.receiver.doSomething();
        }    
    }
    
    public class Invoker{
        private Command command;
        public void setCommand(Command _command){
            this.command=_command;
        }
        public void action(){
            this.command.execute();
        }
    }
    
    public class Client{
        public static void main(String[] args){    
            Invoker invoker=new Invoker();
            Receiver receiver=new ConcreteReceiver1();
            Command command=new ConcreteCommand1(receiver);
            invoker.setCommand(command);
            invoker.action();
        }
    }
  • 相关阅读:
    PHP四种界定符
    设计模式 单例模式与工厂模式
    PHP include与require的区别
    面向对象 static abstract interface 等知识点
    gogland golang 颜色&字体 colors&font 配置文件
    什么是游戏中的帧同步
    kcp协议详解
    kcp流模式与消息模式对比
    kcp源码走读
    kcp结构体字段含义
  • 原文地址:https://www.cnblogs.com/liaojie970/p/5485414.html
Copyright © 2011-2022 走看看