Skip to main content
 首页 » 编程设计

Java 命令模式

2022年07月19日140mate10pro

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

2.试验Demo

import java.util.List; 
import java.util.ArrayList; 
 
class Stock { 
    public void buy() { 
        System.out.println("buy 10 stocks"); 
    } 
 
    public void sell() { 
        System.out.println("shell 10 stocks"); 
    } 
} 
 
 
interface Order { 
    public void excuate(); 
} 
 
class ByStocks implements Order { 
    private Stock stock; 
    public ByStocks(Stock stock) { 
        this.stock = stock; 
    } 
    public void excuate() { 
        stock.buy(); 
    } 
} 
 
 
class ShellStocks implements Order { 
    private Stock stock; 
    public ShellStocks(Stock stock) { 
        this.stock = stock; 
    } 
    public void excuate() { 
        stock.sell(); 
    } 
} 
 
class Broker { 
    private static List<Order> lists = new ArrayList<Order>(); 
 
    public static void orderStore(Order order) { 
        lists.add(order); 
    } 
 
    public static void orderExecute() { 
        for (Order list : lists) { 
            list.excuate(); 
        } 
        lists.clear(); 
    } 
 
} 
 
 
public class CommandPatternDemo { 
    public static void main(String args[]) { 
        Stock stock = new Stock(); 
 
        Order buyStock = new ByStocks(stock); 
        Order shellStock = new ShellStocks(stock); 
 
        Broker.orderStore(buyStock); 
        Broker.orderStore(shellStock); 
 
        Broker.orderExecute(); 
    } 
}

参考:http://www.runoob.com/design-pattern/command-pattern.html


本文参考链接:https://www.cnblogs.com/hellokitty2/p/10721000.html
阅读延展