命令模式

定义:将一个请求封装为一个对象,使发出请求的责任和执行请求的责任分割开。这样两者之间通过命令对象进行沟通,这样方便将命令对象进行储存、传递、调用、增加与管理。

主要解决:在软件系统中,行为请求者与行为实现者通常是一种紧耦合的关系,但某些场合,比如需要对行为进行记录、撤销或重做、事务等处理时,这种无法抵御变化的紧耦合的设计就不太合适。

cs 复制代码
namespace ConsoleApp1
{
	// 实现者
	public interface ILight
	{
		void On();
		void Off();
	}

	class KitchenLight : ILight
	{
		public void On()
		{
			Console.WriteLine("Kitchen light is on");
		}

		public void Off()
		{
			Console.WriteLine("Kitchen light is off");
		}

	}

	class LivingRoomLight : ILight
	{
		public void On()
		{
			Console.WriteLine("Living room light is on");
		}

		public void Off()
		{
			Console.WriteLine("Living room light is off");
		}

	}

	// 命令抽象类
	public interface ICommand
	{
		void execute();
		void undo();
	}

	// 具体命令对象
	class LightOnCommand : ICommand
	{
		private ILight light;

		public LightOnCommand(ILight light) {
			this.light = light;
		}

        public void execute()
		{
			light.On();
        }

        public void undo()
        {
			light.Off();
		}
    }

	class LightOffCommand : ICommand
	{
		private ILight light;

		public LightOffCommand(ILight light)
		{
			this.light = light;
		}

		public void execute()
		{
			light.Off();
		}

		public void undo()
		{
			light.On();
		}
	}

	// 请求者
	class RemoteControl
	{
		private ICommand command;

		public void SetCommand(ICommand command) {
			this.command = command;
		}

		public void PressButton()
		{
			command.execute();
		}

		public void PressUndo()
		{
			command.undo();
		}
	}


	// 客户类(Client)
	class Program
	{
		static void Main(string[] args)
		{
			KitchenLight kitchenLight = new KitchenLight();
			LivingRoomLight livingRoomLight = new LivingRoomLight();

			LightOnCommand lightOnCommand = new LightOnCommand(kitchenLight);
			LightOffCommand lightOffCommand = new LightOffCommand(kitchenLight);

			LightOnCommand lightOnCommand2 = new LightOnCommand(livingRoomLight);
			LightOffCommand lightOffCommand2 = new LightOffCommand(livingRoomLight);

			RemoteControl remoteControl = new RemoteControl();

			remoteControl.SetCommand(lightOnCommand);
			remoteControl.PressButton();
			remoteControl.PressUndo();

			remoteControl.SetCommand(lightOnCommand2);
			remoteControl.PressButton();
			remoteControl.PressUndo();

		}
	}
}
相关推荐
太过平凡的小蚂蚁1 天前
解耦的艺术:深入理解设计模式之命令模式
设计模式·命令模式
序属秋秋秋3 天前
《Linux系统编程之入门基础》【Linux基础 理论+命令】(上)
linux·运维·服务器·ubuntu·centos·命令模式
路明非1265 天前
QT界面实现2
命令模式
金涛03195 天前
QT-day2,信号和槽
开发语言·qt·命令模式
笨手笨脚の9 天前
设计模式-命令模式
设计模式·命令模式·行为型设计模式
web前端神器10 天前
webpack,vite,node等启动服务时运行一段时间命令窗口就卡住
命令模式·命令
青草地溪水旁13 天前
第十五章:令行禁止,运筹帷幄——Command的命令艺术
命令模式
jh_cao14 天前
(1)SwiftUI 的哲学:声明式 UI vs 命令式 UI
ui·swiftui·命令模式
青草地溪水旁15 天前
第十六章:固本培元,守正出奇——Template Method的模板艺术
命令模式
bkspiderx18 天前
C++设计模式之行为型模式:命令模式(Command)
c++·设计模式·命令模式