Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
186 changes: 186 additions & 0 deletions design-patterns/CommandPattern-CSharp/Program.cs
Original file line number Diff line number Diff line change
@@ -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<Command> _commands = new List<Command>();
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++;
}
}
}
Binary file not shown.
39 changes: 39 additions & 0 deletions design-patterns/CommandPattern-CSharp/Readme.md
Original file line number Diff line number Diff line change
@@ -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")
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
129 changes: 129 additions & 0 deletions design-patterns/IteratorPattern-CSharp/Program.cs
Original file line number Diff line number Diff line change
@@ -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<Professor> listProfessors = new List<Professor>();
//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();
}
}

}
Binary file not shown.
31 changes: 31 additions & 0 deletions design-patterns/IteratorPattern-CSharp/Readme.md
Original file line number Diff line number Diff line change
@@ -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")
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading