命令模式

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

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

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();

		}
	}
}
相关推荐
无小道9 小时前
QT——QFIie和QFileInfo文件类
开发语言·qt·命令模式
不绝1912 天前
UGUI相关——基础篇
命令模式
YigAin5 天前
Unity23种设计模式之 命令模式
设计模式·命令模式
懵萌长颈鹿9 天前
命令模式 (Command Pattern)
命令模式
会员果汁14 天前
19.设计模式-命令模式
设计模式·命令模式
羊群智妍15 天前
2026GEO监测工具精选:免费AI搜索优化监测工具实用指南
百度·微信·命令模式·新浪微博·segmentfault
Engineer邓祥浩18 天前
设计模式学习(16) 23-14 命令模式
学习·设计模式·命令模式
小码过河.19 天前
设计模式——命令模式
设计模式·命令模式
刀法孜然21 天前
23种设计模式 3 行为型模式 之3.7 command 命令模式
设计模式·命令模式
JavaBoy_XJ1 个月前
行为型-命令模式
命令模式