命令模式(CommandPattern)

今天主要学习命令模式,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");
	
	@Override
	public void execute() {
		light.on();

	}

}

package Commands;

import Dianqi.Light;
import base.Command;

public class LightOffCommond implements Command {

	public Light light = new Light("room");
	
	@Override
	public 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()即可。由于这样,也添加了高扩展性。这点让我感觉和策略模式有点像。能够參考下当时我总结的策略模式哈。

然后然后,这仅仅是这样一个模型,以了解最重要的。细节还没有练手项目,有个很大的改进余地。

版权声明:本文博客原创文章,博客,未经同意,不得转载。

原文地址:https://www.cnblogs.com/lcchuguo/p/4682361.html