diff --git a/design-patterns/CommandPattern-CSharp/Command Pattern UML Class.png b/design-patterns/CommandPattern-CSharp/Command Pattern UML Class.png new file mode 100644 index 0000000..62ecb5b Binary files /dev/null and b/design-patterns/CommandPattern-CSharp/Command Pattern UML Class.png differ diff --git a/design-patterns/CommandPattern-CSharp/Program.cs b/design-patterns/CommandPattern-CSharp/Program.cs new file mode 100644 index 0000000..7dd27aa --- /dev/null +++ b/design-patterns/CommandPattern-CSharp/Program.cs @@ -0,0 +1,186 @@ +using System; +using System.Collections.Generic; + +namespace Command_Design_Pattern +{ + /// Main Program class for the command design pattern + class Program + + { + static void Main() + { + // Compute expression with the "PEMDAS" mathematical operations sequence + // Create a new use for it + + OperationRule PEMDAS = new OperationRule(); + + // Calculate + + PEMDAS.Compute('+', 500); + PEMDAS.Compute('+', 50); + PEMDAS.Compute('-', 40); + PEMDAS.Compute('-', 10); + + // Check the answers by reversing the sequence to proove "PEMDAS" rule + + PEMDAS.ReverseOp(4); + + // Inverse 3 commands + + PEMDAS.Inverse(4); + + // Wait for PEMDAS + + Console.ReadKey(); + } + } + + // The 'Command' abstract class + + abstract class Command + + { + public abstract void Execute(); + public abstract void UnExecute(); + } + + // The 'ConcreteCommand' class + + class PEMDASCalculator : Command + + { + private char _operator; + private int _operand; + private Calculator _calculator; + + // Constructor + + public PEMDASCalculator(Calculator calculator, + char @operator, int operand) + { + this._calculator = calculator; + this._operator = @operator; + this._operand = operand; + } + + // operator + + public char Operator + { + set { _operator = value; } + } + + // operand + + public int Operand + { + set { _operand = value; } + } + + // new command + + public override void Execute() + { + _calculator.Operation(_operator, _operand); + } + + // Unexecute last command + + public override void UnExecute() + { + _calculator.Operation(ReverseOp(_operator), _operand); + } + + // Returns opposite operator for given operator + + private char ReverseOp(char @operator) + { + switch (@operator) + { + case '+': return '-'; + case '-': return '+'; + default: throw new + + ArgumentException("@operator"); + } + } + } + + // The 'Receiver' class + + class Calculator + + { + private int _curr = 0; + + public void Operation(char @operator, int operand) + { + switch (@operator) + { + + case '+': _curr += operand; break; + case '-': _curr -= operand; break; + } + + Console.WriteLine( + "Current value = {0,3} (following {1} {2})", + _curr, @operator, operand); + } + } + +// The 'Invoker' class + + class OperationRule + + { + // Initializers + + private Calculator _calculator = new Calculator(); + private List _commands = new List(); + private int _current = 0; + + public void Inverse(int levels) + { + Console.WriteLine("\n Inverse {0} levels ", levels); + // Perform redo operations + + for (int i = 0; i < levels; i++) + { + if (_current < _commands.Count - 1) + { + Command command = _commands[_current++]; + command.Execute(); + } + } + } + + public void ReverseOp(int levels) + { + Console.WriteLine("\n ReverseOp {0} levels ", levels); + // Perform ReverseOp operations + + for (int i = 0; i < levels; i++) + { + if (_current > 0) + { + Command command = _commands[--_current] as Command; + command.UnExecute(); + } + } + } + + public void Compute(char @operator, int operand) + { + // Create command operation and execute it + + Command command = new PEMDASCalculator( + _calculator, @operator, operand); + command.Execute(); + + // Add command to ReverseOp list + + _commands.Add(command); + _current++; + } + } +} diff --git a/design-patterns/CommandPattern-CSharp/Program.exe b/design-patterns/CommandPattern-CSharp/Program.exe new file mode 100644 index 0000000..9d274aa Binary files /dev/null and b/design-patterns/CommandPattern-CSharp/Program.exe differ diff --git a/design-patterns/CommandPattern-CSharp/Readme.md b/design-patterns/CommandPattern-CSharp/Readme.md new file mode 100644 index 0000000..f4583c6 --- /dev/null +++ b/design-patterns/CommandPattern-CSharp/Readme.md @@ -0,0 +1,39 @@ +#Command Pattern + +The command pattern is a behavioural design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters. + +Definition + +- Encapsulate a request as an object, thereby letting you parameterise clients with different requests, queue or log requests, and support undoable operations. + +Using the Command design pattern can solve these problems: + +- Coupling the invoker of a request to a particular request should be avoided. That is, hard-wired requests should be avoided. +- It should be possible to configure an object (that invokes a request) with a request. + +Using the Command design pattern describes the following solution: + +- Define separate (command) objects that encapsulate a request. +- A class delegates a request to a command object instead of implementing a particular request directly. +- This enables one to configure a class with a command object that is used to perform a request. +- The class is no longer coupled to a particular request and has no knowledge (is independent) of how the request is carried out. + +The classes and objects participating in this pattern are: + +1) Client +- This is the class that creates and executes the command object. + +2) Invoker +- Asks the command to carry out the action. + +3) Command +- This is an interface which specifies the Execute operation. + +4) ConcreteCommand +- Defines a binding between a Receiver object and an action +- This is a class that implements the Execute operation by invoking operation(s) on the Receiver. + +5) Receiver +- This is a class that performs the Action associated with the request. + +![UML for the Command Pattern ](Command Pattern UML Class.png "UML class diagram of Command Pattern") diff --git a/design-patterns/IteratorPattern-CSharp/Iterator Pattern UML Class.png b/design-patterns/IteratorPattern-CSharp/Iterator Pattern UML Class.png new file mode 100644 index 0000000..6cbc92d Binary files /dev/null and b/design-patterns/IteratorPattern-CSharp/Iterator Pattern UML Class.png differ diff --git a/design-patterns/IteratorPattern-CSharp/Program.cs b/design-patterns/IteratorPattern-CSharp/Program.cs new file mode 100644 index 0000000..9d7b0e7 --- /dev/null +++ b/design-patterns/IteratorPattern-CSharp/Program.cs @@ -0,0 +1,129 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; + +namespace Iterator_Design_Pattern +{ + + // Create the collection item + class Professor + { + public int CourseID { get; set; } + public string CourseName { get; set; } + public Professor(string name, int courseid) + { + CourseName = name; + CourseID = courseid; + } + } + + //Creating Abstract Iterator + + interface AbstractIterator + { + Professor First(); + Professor Next(); + bool IsCompleted { get; } + } + + +// Creating Concrete Iterator + +class Iterator : AbstractIterator + { + private ConcreteCollection collection; + private int current = 0; + private int step = 1; + // Constructor + public Iterator(ConcreteCollection collection) + { + this.collection = collection; + } + // Gets first item + public Professor First() + { + current = 0; + return collection.GetProfessor(current); + } + // Gets next item + public Professor Next() + { + current += step; + if (!IsCompleted) + { + return collection.GetProfessor(current); + } + else + { + return null; + } + } + // Check whether iteration is complete + public bool IsCompleted + { + get { return current >= collection.Count; } + } + } + + // Creating Aggregate + + interface AbstractCollection + { + Iterator CreateIterator(); + } + + // Creating ConcreteAggregate + + + class ConcreteCollection : AbstractCollection + { + private List listProfessors = new List(); + //Create Iterator + public Iterator CreateIterator() + { + return new Iterator(this); + } + // Gets item count + public int Count + { + get { return listProfessors.Count; } + } + //Add items to the collection + public void AddProfessor(Professor professor) + { + listProfessors.Add(professor); + } + //Get item from collection + public Professor GetProfessor(int IndexPosition) + { + return listProfessors[IndexPosition]; + } + } + + public class Program + { + static void Main() + { + // Build a collection + ConcreteCollection collection = new ConcreteCollection(); + collection.AddProfessor(new Professor("Dr.J", 310)); + collection.AddProfessor(new Professor("Prof. Sue", 301)); + collection.AddProfessor(new Professor("Dr. Renne", 611)); + collection.AddProfessor(new Professor("Dr. Kevin", 630)); + collection.AddProfessor(new Professor("Prof. Brian", 465)); + collection.AddProfessor(new Professor("Prof. David", 448)); + + // Create iterator + Iterator iterator = collection.CreateIterator(); + //looping iterator + Console.WriteLine("Iterating over collection:"); + + for (Professor prof = iterator.First(); !iterator.IsCompleted; prof = iterator.Next()) + { + Console.WriteLine($"CourseID : {prof .CourseID} & CourseName : {prof .CourseName}"); + } + Console.Read(); + } + } + + } diff --git a/design-patterns/IteratorPattern-CSharp/Program.exe b/design-patterns/IteratorPattern-CSharp/Program.exe new file mode 100644 index 0000000..10b46b0 Binary files /dev/null and b/design-patterns/IteratorPattern-CSharp/Program.exe differ diff --git a/design-patterns/IteratorPattern-CSharp/Readme.md b/design-patterns/IteratorPattern-CSharp/Readme.md new file mode 100644 index 0000000..f2f50d9 --- /dev/null +++ b/design-patterns/IteratorPattern-CSharp/Readme.md @@ -0,0 +1,31 @@ +#Iterator Pattern + +Overview +- The iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements. The iterator pattern decouples algorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled. + +Definition + +- The essence of the Iterator Pattern is to "Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation." + +What solution does the Iterator design pattern describe? + +- Define a separate (iterator) object that encapsulates accessing and traversing an aggregate object. +- Clients use an iterator to access and traverse an aggregate without knowing its representation (data structures). + +The classes and objects participating in this pattern are: + +1) Iterator +- Defines an interface for accessing and traversing elements. + +2) ConcreteIterator +- Implements the Iterator interface. +- Keeps track of the current position in the traversal of the aggregate. + +3) Aggregate +- Defines an interface for creating an Iterator object + +4) ConcreteAggregate +- Implements the Iterator creation interface to return an instance of the proper ConcreteIterator + + +![UML for the Iterator Pattern ](Iterator Pattern UML Class.png "UML class diagram of Iterator Pattern") diff --git a/design-patterns/MediatorPattern-CSharp/Mediator Pattern UML Class.png b/design-patterns/MediatorPattern-CSharp/Mediator Pattern UML Class.png new file mode 100644 index 0000000..73ecdc6 Binary files /dev/null and b/design-patterns/MediatorPattern-CSharp/Mediator Pattern UML Class.png differ diff --git a/design-patterns/MediatorPattern-CSharp/Program.cs b/design-patterns/MediatorPattern-CSharp/Program.cs new file mode 100644 index 0000000..e9ce79d --- /dev/null +++ b/design-patterns/MediatorPattern-CSharp/Program.cs @@ -0,0 +1,116 @@ +using System; + +namespace Mediator_Design_Pattern +{ + // The Mediator interface + + public interface IMediator + { + void Notify(object sender, string ev); + } + + // Concrete Mediators + + class ConcreteMediator : IMediator + { + private Tab_1 _tab_1; + + private Tab_2 _tab_2; + + public ConcreteMediator(Tab_1 tab_1, Tab_2 tab_2) + { + this._tab_1 = tab_1; + this._tab_1.SetMediator(this); + this._tab_2 = tab_2; + this._tab_2.SetMediator(this); + } + + public void Notify(object sender, string ev) + { + if (ev == "Deposit ") + { + Console.WriteLine("\nMediator reacts on Deposit and triggers folowing operations:"); + this._tab_2.DoCheque(); + } + if (ev == "DemandDraft") + { + Console.WriteLine("\nMediator reacts on DemandDraft and triggers following operations:"); + this._tab_1.DoWithdraw (); + this._tab_2.DoCheque(); + } + } + } + + // The Base Tab provides the basic functionality of storing a + // mediator's instance inside tab objects. + class BaseTab + { + protected IMediator _mediator; + + public BaseTab(IMediator mediator = null) + { + this._mediator = mediator; + } + + public void SetMediator(IMediator mediator) + { + this._mediator = mediator; + } + } + + // Concrete Tabs implement various functionality. They don't depend on + // other tabs. They also don't depend on any concrete mediator + // classes. + class Tab_1 : BaseTab + { + public void DoDeposit () + { + Console.WriteLine("Window_1 deposits the Amount. "); + + this._mediator.Notify(this, "Deposit "); + } + + public void DoWithdraw () + { + Console.WriteLine("Window_1 withdraws the Amount. "); + + this._mediator.Notify(this, "Withdraw "); + } + } + + class Tab_2 : BaseTab + { + public void DoCheque () + { + Console.WriteLine("Window_2 deposits the Cheque. \n"); + + this._mediator.Notify(this, "Cheque"); + } + + public void DemandDraft() + { + Console.WriteLine("Window_2 withdraws the DemandDraft. \n"); + + this._mediator.Notify(this, "DemandDraft"); + } + } + + class Program + { + static void Main(string[] args) + { + // The Customer code. + Tab_1 tab_1 = new Tab_1(); + Tab_2 tab_2 = new Tab_2(); + new ConcreteMediator(tab_1, tab_2); + + Console.WriteLine("Customer triggers New Deposit."); + tab_1.DoDeposit (); + + Console.WriteLine(); + + Console.WriteLine("Customer triggers New Withdraw."); + tab_2.DemandDraft(); + } + } +} diff --git a/design-patterns/MediatorPattern-CSharp/Program.exe b/design-patterns/MediatorPattern-CSharp/Program.exe new file mode 100644 index 0000000..643516a Binary files /dev/null and b/design-patterns/MediatorPattern-CSharp/Program.exe differ diff --git a/design-patterns/MediatorPattern-CSharp/Readme.md b/design-patterns/MediatorPattern-CSharp/Readme.md new file mode 100644 index 0000000..0949067 --- /dev/null +++ b/design-patterns/MediatorPattern-CSharp/Readme.md @@ -0,0 +1,29 @@ +#Mediator Pattern + +The mediator pattern defines an object that encapsulates how a set of objects interact. This pattern is considered to be a behavioural pattern due to the way it can alter the program's running behaviour. + +With the mediator pattern, communication between objects is encapsulated within a mediator object. Objects no longer communicate directly with each other, but instead communicate through the mediator. This reduces the dependencies between communicating objects, thereby reducing coupling. + +Definition + +- The essence of the Mediator Pattern is to "define an object that encapsulates how a set of objects interact". It promotes loose coupling by keeping objects from referring to each other explicitly, and it allows their interaction to be varied independently.[3] Client classes can use the mediator to send messages to other clients, and can receive messages from other clients via an event on the mediator class. + +What solution does the Mediator design pattern describe? + +- Define a separate (mediator) object that encapsulates the interaction between a set of objects. +- Objects delegate their interaction to a mediator object instead of interacting with each other directly. + +The classes and objects participating in this pattern are: + +1) Mediator +- Defines an interface for communicating with Colleague objects + +2) ConcreteMediator +- Implements cooperative behaviour by coordinating Colleague objects +- Knows and maintains its colleagues + +3) Colleague classes +- Each Colleague class knows its Mediator object +- Each colleague communicates with its mediator whenever it would have otherwise communicated with another colleague + +![UML for Mediator Pattern ](Mediator Pattern UML Class.png "UML class diagram of Mediator Pattern") diff --git a/design-patterns/observerPattern-CSharp/Observer Pattern UML Class.png b/design-patterns/observerPattern-CSharp/Observer Pattern UML Class.png new file mode 100644 index 0000000..f9f5d4e Binary files /dev/null and b/design-patterns/observerPattern-CSharp/Observer Pattern UML Class.png differ diff --git a/design-patterns/observerPattern-CSharp/Program.cs b/design-patterns/observerPattern-CSharp/Program.cs new file mode 100644 index 0000000..44ee542 --- /dev/null +++ b/design-patterns/observerPattern-CSharp/Program.cs @@ -0,0 +1,144 @@ +using System; +using System.Collections.Generic; + +namespace Observer_Design_pattern +{ + /// Observer Design Pattern. + + class Program + + { + + static void Main() + { + // Create PizzaHut rate and attach customers + + PizzaHut pizzahut = new PizzaHut("PizzaHut", 20.00); + pizzahut.Attach(new Customer("Veg-Pizza")); + pizzahut.Attach(new Customer("NonVeg-Pizza")); + + // Fluctuating prices will notify customers + + pizzahut.Price = 20.05; + pizzahut.Price = 21.00; + pizzahut.Price = 22.50; + pizzahut.Price = 23.75; + + // Wait for user + + Console.ReadKey(); + } + } + + /// The 'Subject' abstract class + + abstract class Cost + + { + private string _symbol; + private double _price; + private List _customers = new List(); + + // Constructor + + public Cost(string symbol, double price) + { + this._symbol = symbol; + this._price = price; + } + + public void Attach(ICustomer customer ) + { + _customers .Add(customer ); + } + + public void Detach(ICustomer customer ) + { + _customers .Remove(customer ); + } + + public void Update() + { + foreach (ICustomer customer in _customers ) + { + customer .Update(this); + } + + Console.WriteLine(""); + } + + // Gets or sets the price + + public double Price + { + get { return _price; } + set + + { + if (_price != value) + { + _price = value; + Update(); + } + } + } + + // Gets the symbol + + public string Symbol + { + get { return _symbol; } + } + } + + // The 'ConcreteSubject' class + + class PizzaHut : Cost + + { + // Constructor + + public PizzaHut(string symbol, double price) + : base(symbol, price) + { + } + } + + // The 'Observer' interface + + interface ICustomer + + { + void Update(Cost rate); + } + + // The 'ConcreteObserver' class + + class Customer : ICustomer + + { + private string _name; + private Cost _rate; + + // Constructor + + public Customer(string name) + { + this._name = name; + } + + public void Update(Cost rate) + { + Console.WriteLine("Updates on price.. {0} of {1}'s " + + "change to {2:C}", _name, rate.Symbol, rate.Price); + } + + // Gets or sets the rate + + public Cost Cost + { + get { return _rate; } + set { _rate = value; } + } + } +} diff --git a/design-patterns/observerPattern-CSharp/Program.exe b/design-patterns/observerPattern-CSharp/Program.exe new file mode 100644 index 0000000..230d877 Binary files /dev/null and b/design-patterns/observerPattern-CSharp/Program.exe differ diff --git a/design-patterns/observerPattern-CSharp/Readme.md b/design-patterns/observerPattern-CSharp/Readme.md new file mode 100644 index 0000000..03517ba --- /dev/null +++ b/design-patterns/observerPattern-CSharp/Readme.md @@ -0,0 +1,30 @@ +#Observer Pattern + +The Observer Pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. + +The Observer design pattern is one of the twenty-three well-known "Gang of Four" design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse + +What solution does the Observer design pattern describe? + +- Define Subject and Observer objects. +- So that when a subject changes state, all registered observers are notified and updated automatically (and probably asynchronously). + +The classes and objects participating in this pattern are: + +1) Subject +- Knows its observers. Any number of Observer objects may observe a subject +- Provides an interface for attaching and detaching Observer objects. + +2) ConcreteSubject +- Stores state of interest to ConcreteObserver +- Sends a notification to its observers when its state changes + +3) Observer +- Defines an updating interface for objects that should be notified of changes in a subject. + +4) ConcreteObserver +- Maintains a reference to a ConcreteSubject object +- Stores state that should stay consistent with the subject's +- Implements the Observer updating interface to keep its state consistent with the subject's + +![UML for the Observer Pattern ](Observer Pattern UML Class.png "UML class diagram of Observer Pattern")