命令(Command)模式

xiaoxiao2022-06-12  42

13、命令(Command)模式

 

       命令模式(Command)是对命令的封装,命令模式把发出命令的责任和执行命令的责任分开,委派给不同的对象。

 

       命令模式的五个角色:

客户角色(Client):创建一个具体命令对象(Concrete Command),并确定其接收者。      命令角色(Command):声明一个给所有具体命令类的抽象接口,这是一个抽象角色,由抽象和接口实现。具体命令(ConcreteCommand):定义一个接收者和行为之间的弱耦合;实现execute()方法,负责调用接收者的相应操作。请求者角色(Invoker): 负责调用命令对象执行请求。接收者(Receiver):负责具体实施和执行一个请求

     实例代码:

/* 抽象命令角色 */ public interface Command { void execute(); }

 

/* 具体命令角色 */ public class ConcreteCommand implements Command { public ConcreteCommand(Receiver receiver) { this.receiver = receiver; } public void execute() { receiver.action(); } /** * @directed * @clientRole receiver */ private Receiver receiver; }

 

public class Receiver { public Receiver() { //write code here } public void action() { System.out.println("Action has been taken."); } }

 

/* 请求者角色 */ public class Invoker { public Invoker(Command command) { this.command = command; } public void action() { command.execute(); } /** * @link aggregation * @directed */ private Command command; }

 

/* 客户端 */ public class Client { public static void main(String[] args) { Receiver receiver = new Receiver(); Command command = new ConcreteCommand(receiver); Invoker invoker = new Invoker( command ); invoker.action(); } /** @link dependency */ /*#Receiver lnkReceiver;*/ /** @link dependency */ /*#Invoker lnkInvoker;*/ }

 

转载请注明原文地址: https://www.6miu.com/read-4933448.html

最新回复(0)