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

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

文章目录

介绍

先设想一个场景,为系统设计一个命令行界面,用户输入命令来执行某项功能。系统的功能会不断添加,命令也会不断增加,如何将一项一项的功能加入到这个命令行界面?你可能会写出下面一段代码:

public class Receiver{
public void receive(String command) {
switch (command) {
case "command-1": …… break; case "command-2": …… break; case "command-3": …… break; …… } System.out.println("不支持此命令" + command); }}

按照这种写法,如果新增或修改对应的命令,则需要改动到这里的代码,耦合度比较好,不够灵活。

这时候就需要用到命令模式,以命令的方式,解耦调用者与功能具体实现者,降低系统耦合度,提供了灵活性

适用场景

Servlet、Controller、线程池

模式类图

在这里插入图片描述

实例代码

public class Receiver{
//命令和对应的处理类集合 private Map
commands; //注册命令和对应的处理类 public void register(String strComm,Command command){
commands.put(strComm,command); } public void receive(String command) {
Command commandObj = commands.get(command); if(commandObj != null){
commandObj.execute(); return; } System.out.println("不支持此命令" + command); }}

和策略模式区别

  • 策略模式侧重的是一个行为的多个算法实现,可互换算法
  • 命令模式侧重的是多个行为提供灵活的执行方式

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

你可能感兴趣的文章
多目标跟踪的简单理解
查看>>
Near-Online Multi-target Tracking with Aggregated Local Flow Descriptor
查看>>
Joint Tracking and Segmentation of Multiple Targets
查看>>
Subgraph Decomposition for Multi-Target Tracking
查看>>
JOTS: Joint Online Tracking and Segmentation
查看>>
CDT: Cooperative Detection and Tracking for Tracing Multiple Objects in Video Sequences
查看>>
Improving Multi-frame Data Association with Sparse Representations for Robust Near-online Multi-ob
查看>>
Virtual Worlds as Proxy for Multi-Object Tracking Analysis
查看>>
Multi-view People Tracking via Hierarchical Trajectory Composition
查看>>
Online Multi-Object Tracking via Structural Constraint Event Aggregation
查看>>
The Solution Path Algotithm for Identity-Aware Multi-Object Tracking
查看>>
Groupwise Tracking of Crowded Similar-Appearance Targets from Low-Continuity Image Sequences
查看>>
CDTS: Collaborative Detection, Tracking, and Segmentation for Online Multiple Object Segmentation
查看>>
Deep Network Flow for Multi-Object Tracking
查看>>
Multiple People Tracking by Lifted Multicut and Person Re-identification
查看>>
Multi-Object Tracking with Quadruplet Convolutional Neural Networks
查看>>
关于多目标跟踪的一点理解
查看>>
Learning by tracking:Siamese CNN for robust target association
查看>>
MUSTer:Multi-Store Tracker:A Cognitive Psychology Inspired Approach to Object Tracking
查看>>
Understanding and Diagnosing Visual Tracking Systems
查看>>