设计模式-命令模式

 一、命令模式

将“请求”封装成对象,以便使用不同的请求,队列或者日志来参数化其他对象。命令模式也支持可撤销的操作

二、设计原则

多用组合,少用继承

三、代码实现

1、Client

package com.oyhp.client;

import com.oyhp.command.LightOffCommand;
import com.oyhp.command.LightOnCommand;
import com.oyhp.invoker.SimpleRemoteControl;
import com.oyhp.receiver.Light;

//相当于客户
public class RemoteControlTest {
	public static void main(String[] args) {
		SimpleRemoteControl remote = new SimpleRemoteControl();
		Light light = new Light();
		//开灯操作
		LightOnCommand lightOn = new LightOnCommand(light);
		remote.setCommand(lightOn);
		remote.buttonWasPressed();
		//关灯操作
		LightOffCommand lightOff = new LightOffCommand(light);
		remote.setCommand(lightOff);
		remote.buttonWasPressed();
	}
}

2、Invoker

package com.oyhp.invoker;

import com.oyhp.command.Command;
//遥控器
public class SimpleRemoteControl {
	Command slot;						//组合
	
	public SimpleRemoteControl(){
		
	}
	
	public void setCommand(Command command){
		slot = command;
	}
	
	public void buttonWasPressed(){
		slot.execute();
	}
}

3、Receiver

package com.oyhp.receiver;

public abstract class Receiver {
	public abstract void on();
	public abstract void off();
}

package com.oyhp.receiver;

public class Light extends Receiver{
	private String name;
	
	public Light() {
		name = "电灯";
		System.out.println(name);
	}

	@Override
	public void on() {
		// TODO Auto-generated method stub
		System.out.println("开");
	}

	@Override
	public void off() {
		// TODO Auto-generated method stub
		System.out.println("关");
	}
}

4、Command

package com.oyhp.command;
//命令
public interface Command {
	public void execute();
}

package com.oyhp.command;

import com.oyhp.receiver.Light;
//电灯-关-命令
public class LightOffCommand implements Command{
	Light light;
	
	public LightOffCommand(Light light) {
		this.light = new Light();
	}
	
	@Override
	public void execute() {
		light.off();
	}

}

package com.oyhp.command;

import com.oyhp.receiver.Light;
//电灯-开-命令
public class LightOnCommand implements Command{
	Light light;
	
	public LightOnCommand(Light light) {
		this.light = light;
	}
	
	@Override
	public void execute() {
		light.on();
	}

}

四、类图

五、总结

命令模式把每一个操作命令都封装成对象,比如开关灯操作,通过调用者来实现具体的操作,调用者不需要知道如何实现开关操作,只需要“执行”命令就行,从而达到解耦的操作,本章没有演示撤销和party模式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值