命令模式(CommandPattern)

来源:互联网 发布:数据库前置库 编辑:程序博客网 时间:2024/06/08 05:11

今天主要学习了命令模式,java思想的权限访问,还有一些视屏教程,这里把比较重要的命令模式总结一下。

刚开始觉得命令模式很难得样子,但是学习完才发现他是和单例模式一样的,属于设计模式里面最简单的集中模式。

命令模式就是将命令请求封装成命令对象,然后其他的类直接调用该对象实现的接口的方法,达到调用对象的动作的目的。达到解耦合。

用小例子来解释:遥控器,电灯。遥控器要控制电灯的开关,但是遥控器中不应该有关于电灯的具体实现代码,这时就应该把电灯的开和关命令封装起来。

Light类:

package Dianqi;public class Light {private String s;public Light(String s) {this.s = s;}public void on() {System.out.println(s + "开灯");}public void off() {System.out.println(s + "关灯");}}

命令接口:

public interface Command {public void execute();}

封装会的开和关的操作:

package Commands;import Dianqi.Light;import base.Command;public class LightOnCommond implements Command {public Light light = new Light("room");@Overridepublic void execute() {light.on();}}

package Commands;import Dianqi.Light;import base.Command;public class LightOffCommond implements Command {public Light light = new Light("room");@Overridepublic void execute() {light.off();}}

遥控器对应的控制类:

package base;public class RemoteControler {private Command command;public void setCommand(Command command) {this.command = command;}public void pressButton() {command.execute();}}

最后的测试类:

import Commands.LightOffCommond;import Commands.LightOnCommond;import Dianqi.Light;public class TestCase {public static void main (String args[]) {LightOnCommond commandOn = new LightOnCommond();LightOffCommond commandOff = new LightOffCommond();RemoteControler controler = new RemoteControler();controler.setCommand(commandOn);controler.pressButton();controler.setCommand(commandOff);controler.pressButton();}}

总结:我认为,这种模式最好的地方就是通过解开了命令和执行命令的类之间的耦合性,执行者不需要知道命令内容具体是什么,只要管执行execute()就行,因为这样,也增加了高扩展性,这点让我感觉和策略模式有点像,可以参考下当时我总结的策略模式哈。

然后然后,这只是最基本的理解这种模式,还没在具体项目中练过手,还有很多进步空间的。

0 0
原创粉丝点击