Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // github: https://github.com/ivandrofly
- namespace CommandPattern
- {
- using System;
- internal interface ICommand
- {
- void Execute();
- }
- internal interface IReceiver
- {
- void TurnOn();
- void TurnOff();
- }
- internal interface IInvoker
- {
- void ExecuteCommand(ICommand command);
- }
- internal class UniversalController : IInvoker
- {
- public void ExecuteCommand(ICommand command) => command.Execute();
- }
- internal class TurnOnCommand : ICommand
- {
- private readonly IReceiver receiver;
- public TurnOnCommand(IReceiver receiver)
- {
- this.receiver = receiver;
- }
- public void Execute()
- {
- Console.WriteLine($"{nameof(TurnOnCommand)} - executed!");
- receiver.TurnOn();
- }
- }
- internal class TurnOffCommand : ICommand
- {
- private readonly IReceiver receiver;
- public TurnOffCommand(IReceiver receiver)
- {
- this.receiver = receiver;
- }
- public void Execute()
- {
- Console.WriteLine($"{nameof(TurnOffCommand)} - executed!");
- receiver.TurnOff();
- }
- }
- internal class SamsungTv : IReceiver
- {
- private bool _isOn;
- public void TurnOff() => _isOn = false;
- public void TurnOn() => _isOn = true;
- public void WatchTv() => Console.WriteLine(_isOn ? "Watching netflix :)" : "Be sad :(");
- }
- internal class LGSmartTv : IReceiver
- {
- public void TurnOff()
- {
- Console.WriteLine("Black screen (Life is not good :()");
- }
- public void TurnOn()
- {
- Console.WriteLine("Display LG + (Life is good)");
- }
- }
- internal class Program
- {
- private static void Main(string[] args)
- {
- SamsungTv samsungTv = new SamsungTv();
- IReceiver lgTv = new LGSmartTv();
- // universal remove controller
- IInvoker urc = new UniversalController();
- // commands
- TurnOnCommand onCmd = new TurnOnCommand(samsungTv);
- TurnOffCommand offCmd = new TurnOffCommand(samsungTv);
- samsungTv.WatchTv();
- urc.ExecuteCommand(onCmd);
- samsungTv.WatchTv();
- urc.ExecuteCommand(offCmd);
- samsungTv.WatchTv();
- Console.WriteLine("press any key to execute command on lg tv");
- Console.ReadLine();
- urc.ExecuteCommand(new TurnOnCommand(lgTv));
- urc.ExecuteCommand(new TurnOffCommand(lgTv));
- Console.ReadLine();
- }
- }
- }
Add Comment
Please, Sign In to add comment