Command实现遥控器

    public interface ICommand
    {
        void Execute();
    }
    public class LightOnCommand:ICommand
    {
        Light light;

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

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

    public class LightOffCommand : ICommand
    {
        Light light;

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

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

    public class Light
    {

        public void On()
        {
            Console.WriteLine("打开电灯");
        }

        public void Off()
        {

            Console.WriteLine("关闭电灯");
        }
    }

    public class NoCommand:ICommand
    {
        public void Execute()
        {
            
        }
    }

public class RemoteControl
    {
        ICommand[] onCommands;
        ICommand[] offCommands;

        public RemoteControl()
        {
            onCommands = new ICommand[7];
            offCommands = new ICommand[7];
        }

        public void SetCommand(int slot, ICommand oncommand, ICommand offCommand)
        {
            onCommands[slot] = oncommand;
            offCommands[slot] = offCommand;
        
        }

        public void Button1Click(int slot)
        {
            onCommands[slot].Execute();
        }

        public void Button2Click(int slot)
        {
            offCommands[slot].Execute();
        }
       
    }

 class Program
    {
        static void Main(string[] args)
        {
            RemoteControl rc = new RemoteControl();
            Light light = new Light();
            ICommand loc = new LightOnCommand(light);
            ICommand lfc = new LightOffCommand(light);
            ICommand nc = new NoCommand();
            for (int i = 0; i < 7; i++)
            {
                rc.SetCommand(i, nc, nc);
            }

            rc.SetCommand(0, loc, lfc);
            rc.Button1Click(0);
            rc.Button2Click(0);

            Console.Read();
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值