zoukankan      html  css  js  c++  java
  • 设计模式(六)命令模式

    步骤 1

    创建一个命令接口。

    public interface Order {
       void execute();
    }

    步骤 2

    创建一个请求类。

    public class Stock {
       
       private String name = "ABC";
       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");
       }
    }

    步骤 3

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

    BuyStock.java
    
    public class BuyStock implements Order {
       private Stock abcStock;
     
       public BuyStock(Stock abcStock){
          this.abcStock = abcStock;
       }
     
       public void execute() {
          abcStock.buy();
       }
    }
    SellStock.java
    
    public class SellStock implements Order {
       private Stock abcStock;
     
       public SellStock(Stock abcStock){
          this.abcStock = abcStock;
       }
     
       public void execute() {
          abcStock.sell();
       }
    }

    步骤 4

    创建命令调用类。

    import java.util.ArrayList;
    import java.util.List;
     
    public class Broker {
       
        private List<Order> orderList = new ArrayList<Order>(); 
     
       public void takeOrder(Order order){
          orderList.add(order);      
       }
     
       public void placeOrders(){
          for (Order order : orderList) {
             order.execute();
          }
          orderList.clear();
       }
    }

    步骤 5

    使用 Broker 类来接受并执行命令。

    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();
       }
    }

    步骤 6

    执行程序,输出结果:

    Stock [ Name: ABC, Quantity: 10 ] bought
    Stock [ Name: ABC, Quantity: 10 ] sold
  • 相关阅读:
    MVAPICH
    sql server触发器的例子
    Sql Server 判断表或数据库是否存在
    JS验证用户真实姓名
    js实现瀑布流的一种简单方法实例分享
    C#实现登录窗口(不用隐藏)
    判断滚动条到底部的JS代码
    php 中文字符串首字母的获取函数
    C#获取当前页面的URL
    C#动态生成图书信息XML文件
  • 原文地址:https://www.cnblogs.com/ganchuanpu/p/7455984.html
Copyright © 2011-2022 走看看