一、概念
- 将请求与执行分开,将客户端与服务端进行解耦;客户端---->命令----->服务端;
二、场景
- 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);
- 商品服务类,类名:ProductService
四、优缺点
- 优点
- 降低了客户端与服务端的耦合度。
- 新的命令可以很容易添加到系统中去。
- 缺点
- 会有一些具体的命令类,增加了系统的复杂度。
本文介绍了命令模式的概念,它通过将请求与执行分离,实现客户端与服务端的解耦。文中给出了在电商系统中查询商品和获取购物车数据的场景,展示了如何通过命令模式来实现这一功能。此外,还探讨了命令模式的优缺点,如降低耦合度和易于扩展,但也指出可能增加系统复杂性的缺点。
554

被折叠的 条评论
为什么被折叠?



