博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
命令模式
阅读量:6851 次
发布时间:2019-06-26

本文共 2145 字,大约阅读时间需要 7 分钟。

hot3.png

命令模式将请求封装成一个对象,实现了命令发出者和实现者的解耦

先看实现者:

package com.whereta.command;/** * Vincent 创建于 2016/5/4. * 接受者:用于处理具体逻辑 */public abstract class Recevier {    protected  abstract void doSomething();}
package com.whereta.command;/** * Vincent 创建于 2016/5/4. */public class Receiver1 extends Recevier {    protected void doSomething() {        System.out.println("Receiver1...");    }}
package com.whereta.command;/** * Vincent 创建于 2016/5/4. */public class Receiver2 extends Recevier {    protected void doSomething() {        System.out.println("Receiver2...");    }}
package com.whereta.command;/** * Vincent 创建于 2016/5/4. */public class Receiver3 extends Recevier {    protected void doSomething() {        System.out.println("Receiver3...");    }}

命令对象:

package com.whereta.command;/** * Vincent 创建于 2016/5/4. * 命令类 */public abstract class Command {    protected Recevier recevier1=new Receiver1();    protected Recevier recevier2=new Receiver2();    protected Recevier recevier3=new Receiver3();    protected abstract void execute();}
package com.whereta.command;/** * Vincent 创建于 2016/5/4. */public class Command1 extends Command {    protected void execute() {        super.recevier1.doSomething();    }}
package com.whereta.command;/** * Vincent 创建于 2016/5/4. */public class Command2 extends Command {    protected void execute() {        super.recevier2.doSomething();    }}
package com.whereta.command;/** * Vincent 创建于 2016/5/4. */public class Command3 extends Command {    protected void execute() {        super.recevier3.doSomething();    }}

调用者:

package com.whereta.command;/** * Vincent 创建于 2016/5/4. */public class Invoker {    private Command command;    public Invoker(Command command) {        this.command = command;    }    public void action(){        command.execute();    }}

测试:

package com.whereta.command;/** * Vincent 创建于 2016/5/4. */public class Main {    public static void main(String[] args) {        Command command=new Command1();        Invoker invoker=new Invoker(command);        invoker.action();    }}

输出:

Receiver1...

从上可以看出:命令类里的具体实现要依赖接受者

策略模式的策略类已经有了具体实现不依靠第三方

个人博客:

转载于:https://my.oschina.net/vincentzhao/blog/669855

你可能感兴趣的文章
界面间传值
查看>>
3.vsphere client的安装
查看>>
Linux实现最常用的磁盘阵列-- RAID5
查看>>
简单的菜单 menu
查看>>
Intellij Idea 2017创建非Maven web项目使用tomcat部署实战
查看>>
工程DHCP配置
查看>>
GIL(全局解释器锁)与互斥锁
查看>>
我的友情链接
查看>>
Git常用操作及分支
查看>>
关于一种求最大公约数的算法的分析与证明
查看>>
微信授权莫名创建用户数据失败的原因
查看>>
网络高手修身
查看>>
JavaWeb综合案例-键盘模拟
查看>>
Android Day03-SQLite数据库操作及ListView详解
查看>>
Looking for APAC Operations IT XML Database Developer in Shenzhen and Hongkong
查看>>
Myeclipse常用快捷键
查看>>
我的友情链接
查看>>
Unity3d多线程
查看>>
炉石传说 C# 开发笔记 (源代码整理公开)
查看>>
前端文摘:Web 开发模式演变历史和趋势
查看>>