8.命令模式
1.将一个请求封装为一个对象,使发出请求的责任和执行请求的责任分割开。这样两者之间通过命令对象进行沟通,这样方便将命令对象进行储存、传递、调用、增加与管理。这样可以将方法的请求者和方法的实现者分离开,实现解耦。而且请求的增减对现有的方法不会产生影响,满足开闭原则。一般命令模式的的实现方式如下:命令-->接受这-->实现者。
2.下面已兵工厂为实例实现简单的命令模式。兵工厂有两个部门,一个生产枪支,一个生产弹药,国防部首先下达生产命令给兵工厂的经理,兵工厂经理接受命令后命令具体的生产部门开动生产线,完成任务。模式如下:国防部下命令(command)--> 兵工厂经理(receiver)--> 生产部门(execute)。
3.实现
(1) 生产部门
package com.java.dp.command; /** * @Author lizhilong * @create 2019/12/6 14:12 * @desc 执行者接口 */ public abstract class Department { public abstract void create(); }
package com.java.dp.command; /** * @Author lizhilong * @create 2019/12/6 14:13 * @desc 执行者实现 */ public class GunDepartment extends Department { @Override public void create() { System.out.println("------------本部门负责制造枪支-----------"); } }
package com.java.dp.command; /** * @Author lizhilong * @create 2019/12/6 14:14 * @desc 执行者实现 */ public class BulletsDepartment extends Department { @Override public void create() { System.out.println("--------------本部门负责制造子弹---------------"); } }
(2)命令
package com.java.dp.command; /** * @Author lizhilong * @create 2019/12/6 14:10 * @desc 命令接口 */ public interface Command { void execute(); }
package com.java.dp.command; /** * @Author lizhilong * @create 2019/12/6 14:18 * @desc 枪支生产命令 */ public class GunCommand implements Command { private GunDepartment gunDepartment; public GunCommand(){ gunDepartment = new GunDepartment(); } @Override public void execute() { gunDepartment.create(); } }
package com.java.dp.command; /** * @Author lizhilong * @create 2019/12/6 14:20 * @desc 子弹生产命令 */ public class BulletsCommand implements Command{ private BulletsDepartment bulletsDepartment; public BulletsCommand(){ bulletsDepartment = new BulletsDepartment(); } @Override public void execute() { bulletsDepartment.create(); } }
(3)接受者
package com.java.dp.command; /** * @Author lizhilong * @create 2019/12/6 14:22 * @desc 命令接受者 */ public class CommandReceiver { private Command command; public CommandReceiver(Command command){ this.command = command; } public void call(){ this.command.execute(); } }
(4)客户端
package com.java.dp.command; /** * @Author lizhilong * @create 2019/12/6 14:25 * @desc */ public class CommandClient { public static void main(String[] args) { System.out.println("----------------国防部下命令生产枪支-------------"); Command gunCommand = new GunCommand(); System.out.println("----------------兵工厂经理收到命令---------------"); CommandReceiver receiver = new CommandReceiver(gunCommand); System.out.println("----------------经理下达生产命令---------------"); receiver.call(); System.out.println("\n"); System.out.println("----------------国防部下命令生产弹药-------------"); Command bulletsCommand = new BulletsCommand(); System.out.println("----------------兵工厂经理收到命令---------------"); CommandReceiver receiver2 = new CommandReceiver(bulletsCommand); System.out.println("----------------经理下达生产命令---------------"); receiver2.call(); } }