博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
设计模式之命令模式 Java实例讲解 + 线程池中的应用场景
阅读量:3909 次
发布时间:2019-05-23

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

2.2 命令模式

示例代码git地址 :

文章目录

(1)概念

命令模式(Command Pattern)是一种数据驱动的设计模式,它属于行为型模式。请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。

主要解决:在软件系统中,行为请求者与行为实现者通常是一种紧耦合的关系,但某些场合,比如需要对行为进行记录、撤销或重做、事务等处理时,这种无法抵御变化的紧耦合的设计就不太合适。

(2)适用场景

认为是命令的地方都可以使用命令模式,比如: 1、GUI 中每一个按钮都是一条命令。 2、模拟 CMD。

在某些场合,比如要对行为进行"记录、撤销/重做、事务"等处理,这种无法抵御变化的紧耦合是不合适的。在这种情况下,如何将"行为请求者"与"行为实现者"解耦?将一组行为抽象为对象,可以实现二者之间的松耦合。

注意事项:系统需要支持命令的撤销(Undo)操作和恢复(Redo)操作,也可以考虑使用命令模式,见命令模式的扩展。

(3)代码示例

关键代码:定义三个角色:1、received 真正的命令执行对象 2、Command 3、invoker 使用命令对象的入口

我们首先创建作为命令的接口 Order,然后创建作为请求的 Stock 类。实体命令类 BuyStockSellStock,实现了 Order 接口,将执行实际的命令处理。创建作为调用对象的类 Broker,它接受订单并能下订单。

Broker 对象使用命令模式,基于命令的类型确定哪个对象执行哪个命令。CommandPatternDemo,我们的演示类使用 Broker 类来演示命令模式。

创建一个命令接口。

package com.alibaba.design.commandpattern;/** * @author zhouyanxiang * @create 2020-08-2020/8/1-8:57 */public interface Order {    void execute();}

创建一个请求类。

package com.alibaba.design.commandpattern;/** * @author zhouyanxiang * @create 2020-08-2020/8/1-8:57 */public class Stock {    private String name = "Tom";    private int quantity = 10;    public void buy(){        System.out.println("Stock [ Name: "+name+", Quantity: " + quantity +" ] bought");    }    public void sell(){        System.out.println("Stock [ Name: "+name+", Quantity: " + quantity +" ] sold");    }}

创建实现了 Order 接口的实体类。

  • BuyStock
package com.alibaba.design.commandpattern;/** * @author zhouyanxiang * @create 2020-08-2020/8/1-8:59 */public class BuyStock implements Order {    private Stock abcStock;    public BuyStock(Stock abcStock){        this.abcStock = abcStock;    }    @Override    public void execute() {        abcStock.buy();    }}
  • SellStock
package com.alibaba.design.commandpattern;/** * @author zhouyanxiang * @create 2020-08-2020/8/1-9:00 */public class SellStock implements Order {    private Stock abcStock;    public SellStock(Stock abcStock){        this.abcStock = abcStock;    }    @Override    public void execute() {        abcStock.sell();    }}

创建命令调用类。

package com.alibaba.design.commandpattern;import java.util.ArrayList;import java.util.List;/** * @author zhouyanxiang * @create 2020-08-2020/8/1-9:01 */public class Broker {    private List
orderList = new ArrayList
(); public void takeOrder(Order order){ orderList.add(order); } public void placeOrders(){ for (Order order : orderList) { order.execute(); } orderList.clear(); }}
package com.alibaba.design.commandpattern;/** * @author zhouyanxiang * @create 2020-08-2020/8/1-9:02 */public class CommandPatternDemo {    public static void main(String[] args) {        Stock abcStock = new Stock();        BuyStock buyStockOrder = new BuyStock(abcStock);        SellStock sellStockOrder = new SellStock(abcStock);        Broker broker = new Broker();        broker.takeOrder(buyStockOrder);        broker.takeOrder(sellStockOrder);        broker.placeOrders();    }}

执行程序,输出结果:

(4)该模式在源码中的应用

典型的java.lang.Runable和线程池中都有用到命令模式

来看一下Runable的源码

Runable:任务抽象,也就是“命令”;线程池通过submit和execute调用

java.util.concurrent.ThreadPoolExecutor线程池中的源码

/**     * Executes the given task sometime in the future.  The task     * may execute in a new thread or in an existing pooled thread.     *     * If the task cannot be submitted for execution, either because this     * executor has been shutdown or because its capacity has been reached,     * the task is handled by the current {@code RejectedExecutionHandler}.     *     * @param command the task to execute     * @throws RejectedExecutionException at discretion of     *         {@code RejectedExecutionHandler}, if the task     *         cannot be accepted for execution     * @throws NullPointerException if {@code command} is null     */    public void execute(Runnable command) {
if (command == null) throw new NullPointerException(); /* * Proceed in 3 steps: * * 1. If fewer than corePoolSize threads are running, try to * start a new thread with the given command as its first * task. The call to addWorker atomically checks runState and * workerCount, and so prevents false alarms that would add * threads when it shouldn't, by returning false. * * 2. If a task can be successfully queued, then we still need * to double-check whether we should have added a thread * (because existing ones died since last checking) or that * the pool shut down since entry into this method. So we * recheck state and if necessary roll back the enqueuing if * stopped, or start a new thread if there are none. * * 3. If we cannot queue task, then we try to add a new * thread. If it fails, we know we are shut down or saturated * and so reject the task. */ int c = ctl.get(); if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true)) return; c = ctl.get(); } if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get(); if (! isRunning(recheck) && remove(command)) reject(command); else if (workerCountOf(recheck) == 0) addWorker(null, false); } else if (!addWorker(command, false)) reject(command); } /** * Initiates an orderly shutdown in which previously submitted * tasks are executed, but no new tasks will be accepted. * Invocation has no additional effect if already shut down. * *

This method does not wait for previously submitted tasks to * complete execution. Use {@link #awaitTermination awaitTermination} * to do that. * * @throws SecurityException {@inheritDoc} */ public void shutdown() {

final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try {
checkShutdownAccess(); advanceRunState(SHUTDOWN); interruptIdleWorkers(); onShutdown(); // hook for ScheduledThreadPoolExecutor } finally {
mainLock.unlock(); } tryTerminate(); }

(5)命令模式的优缺点

  • 优点:

    1、降低了系统耦合度。

    2、新的命令可以很容易添加到系统中去。

  • 缺点:

    使用命令模式可能会导致某些系统有过多的具体命令类。

转载地址:http://eeurn.baihongyu.com/

你可能感兴趣的文章
用了Dapper之后通篇还是SqlConnection,真的看不下去了
查看>>
ABP快速开发一个.NET Core电商平台
查看>>
[NewLife.Net]单机400万长连接压力测试
查看>>
使用Azure人脸API对图片进行人脸识别
查看>>
快醒醒,C# 9 中又来了一堆关键词 init,record,with
查看>>
【招聘(深圳)】轻岁 诚聘.NET Core开发
查看>>
await,async 我要把它翻个底朝天,这回你总该明白了吧
查看>>
.NET Core实用技巧(一)如何将EF Core生成的SQL语句显示在控制台中
查看>>
使用Jenkins来发布和代理.NetCore项目
查看>>
欢迎来到 C# 9.0(Welcome to C# 9.0)
查看>>
Dapr微服务应用开发系列1:环境配置
查看>>
使用 Visual Studio 2019 批量添加代码文件头
查看>>
【BCVP更新】StackExchange.Redis 的异步开发方式
查看>>
Istio 1.7——进击的追风少年
查看>>
.NET5.0 Preview 8 开箱教程
查看>>
efcore技巧贴-也许有你不知道的使用技巧
查看>>
真・WPF 按钮拖动和调整大小
查看>>
做权限认证,还不了解IdentityServer4?不二话,赶紧拥抱吧,.NET Core官方推荐!...
查看>>
MongoDB最新4.2.7版本三分片集群修改IP实操演练
查看>>
编写第一个 .NET 微服务
查看>>