设计模式之命令模式

一、概念

  • 将请求与执行分开,将客户端与服务端进行解耦;客户端---->命令----->服务端;

二、场景

  • cmd,在linux上操作
  • 场景实例
    • 工作流审核
    • 命令执行窗口

三、实现

  • 条件
    • java
  • 场景
    • 在电商系统中,以查询商品和获取购物车数据为例来是实现命令模式。
  • 代码实现
    • 商品服务类,类名:ProductService
          package com.CommandPattern;
           
          public class ProductService {
              public void getProduct()
              {
                  System.out.println("查询商品服务!");
              }
          }
      
      
    • 商品服务命令类,类名:ProductCommand
          package com.CommandPattern;
           
          public class ProductCommand implements  ICommand {
              private ProductService productService = new ProductService();
              @Override
              public void excute() {
                  productService.getProduct();
              }
          }
      
      
    • 购物车服务类,类名:ShoppingCarService
          package com.CommandPattern;
           
          public class ShoppingCarService {
              public void  getShoppingCar()
              {
                  System.out.println("这是购物车服务!");
              }
          }
      
      
    • 购物车服务类,类名:ShopingCarCommand
          package com.CommandPattern;
           
          public class ShopingCarCommand implements  ICommand{
              private ShoppingCarService shoppingCarService = new ShoppingCarService();
          
              @Override
              public void excute() {
                  shoppingCarService.getShoppingCar();
              }
          }
      
      
    • 命令接口类,类名:ICommand
          package com.CommandPattern;
           
          public interface ICommand {
              //执行函数
              void excute();
          }
      
      
    • 命令执行器,类名:CommandInvoker
          package com.CommandPattern;
          
          import java.util.ArrayList;
          import java.util.List;
           
          public class CommandInvoker {
              private List<ICommand> list = new ArrayList<>();
              public void Add (ICommand command){
                  list.add(command);
              }
              //执行函数
              public void excuter(int index)
              {
                   list.get(index).excute();
              }
          }
      
      
    • 入口函数类
          CommandInvoker commandInvoker = new CommandInvoker();
          commandInvoker.Add(new ProductCommand());
          commandInvoker.Add(new ShopingCarCommand());
          commandInvoker.excuter(0);
      

四、优缺点

  • 优点
    • 降低了客户端与服务端的耦合度。
    • 新的命令可以很容易添加到系统中去。
  • 缺点
    • 会有一些具体的命令类,增加了系统的复杂度。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值