示例#1
0
        public static void Main(string[] arguments)
        {
            string argument;

            ISwitchable lamp = new Light();

            ICommand switchClose = new CloseSwitchCommand(lamp);
            ICommand switchOpen  = new OpenSwitchCommand(lamp);

            var switchAction = new Switch(switchClose, switchOpen);

            while (!string.IsNullOrEmpty(argument = Console.ReadLine()))
            {
                switch (argument)
                {
                case "ON":
                    switchAction.Open();
                    break;

                case "OFF":
                    switchAction.Close();
                    break;

                default:
                    Console.WriteLine("Argument \"ON\" or \"OFF\" is required.");
                    break;
                }
            }

            Console.ReadKey();
        }
示例#2
0
        static void Main(string[] args)
        {
            ISwitchable lamp = new Light();

            ICommand switchClose = new CloseSwitchCommand(lamp);
            ICommand switchOpen  = new OpenSwitchCommand(lamp);

            var remoteControl = new Switch(switchClose, switchOpen);

            remoteControl.OpenLight();
            remoteControl.CloseLight();
        }
示例#3
0
        private static void SwitchExample()
        {
            ISwitchable lamp = new Light();

            // Pass reference to the lamp instance to each command
            ICommand switchClose = new CloseSwitchCommand(lamp);
            ICommand switchOpen  = new OpenSwitchCommand(lamp);

            // Pass reference to instances of the Command objects to the switch
            var @switch = new Switch();

            Console.Write("Please enter the number of commands: ");
            var numberOfCommands = int.Parse(Console.ReadLine());

            for (int i = 0; i < numberOfCommands; i++)
            {
                Console.Write("Please enter command (OPEN or CLOSE): ");
                var arg = Console.ReadLine(); // OPEN or CLOSE
                if (arg == "OPEN")
                {
                    // Switch (the Invoker) will invoke Execute() (the Command) on the command object
                    @switch.StoreAndExecute(switchOpen);
                }
                else if (arg == "CLOSE")
                {
                    // Switch (the Invoker) will invoke the Execute() (the Command) on the command object
                    @switch.StoreAndExecute(switchClose);
                }
                else
                {
                    Console.WriteLine("Argument \"OPEN\" or \"CLOSE\" is required.");
                }
            }

            Console.WriteLine("Undoing commands...");
            foreach (ICommand command in @switch.History)
            {
                command.UnExecute();
            }
        }