Saturday, May 29, 2021

Memento pattern c#

Memento is a behavioral design pattern that lets you save and restore the previous state of an object without revealing the details of its implementation.
public interface IMemento
{
   string GetName();
   string GetState();
   DateTime GetDate();
}
The Memento interface provides a way to retrieve the memento's metadata, such as creation date or name. However, it doesn't expose the Originator's state. The Originator uses this method when restoring its state. The rest of the methods are used by the Caretaker to display metadata.
class Memento : IMemento
{
   private string _state;
   private DateTime _date;
   public Memento(string state)
   {
       this._state = state;
       this._date = DateTime.Now;
   }
   public string GetState()
   {
       return this._state;
   }
   public string GetName()
   {
       return $"{this._date} / ({this._state.Substring(0, 9)})...";
   }
   public DateTime GetDate()
   {
       return this._date;
   }
}
The Originator holds some important state that may change over time. It also defines a method for saving the state inside a memento and another method for restoring the state from it.
For the sake of simplicity, the originator's state is stored inside a single variable. The Originator's business logic may affect its internal state. Therefore, the client should backup the state before launching methods of the business logic via the save() method.
Saves the current state inside a memento. It also Restores the Originator's state from a memento object.
class Originator
{
    private string _state;
    public Originator(string state)
    {
        this._state = state;
        Console.WriteLine("Originator: My initial state is: " + state);
    }
    public void DoSomething()
    {
        Console.WriteLine("Originator: I'm doing something important.");
        this._state = this.GenerateRandomString(30);
        Console.WriteLine($"Originator: and my state has changed to: {_state}");
    }
    private string GenerateRandomString(int length = 10)
    {
       string allowedSymbols = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
       string result = string.Empty;
       while (length > 0)
       {
           result += allowedSymbols[new Random().Next(0, allowedSymbols.Length)];
           Thread.Sleep(12);
           length--;
       }
       return result;
   }
   public IMemento Save()
   {
       return new Memento(this._state);
   }
   public void Restore(IMemento memento)
   {
       if (!(memento is Memento))
       {
           throw new Exception("Unknown memento class " + memento.ToString());
       }
       this._state = memento.GetState();
       Console.Write($"Originator: My state has changed to: {_state}");
   }
}
The Caretaker doesn't depend on the Concrete Memento class. Therefore, it doesn't have access to the originator's state, stored inside the memento. It works with all mementos via the base Memento interface.
class Caretaker
{
    private List<IMemento> _mementos = new List<IMemento>();
    private Originator _originator = null;
    public Caretaker(Originator originator)
    {
        this._originator = originator;
    }
    public void Backup()
    {
        Console.WriteLine("\nCaretaker: Saving Originator's state...");
        this._mementos.Add(this._originator.Save());
    }
    public void Undo()
    {
        if (this._mementos.Count == 0)
        {
            return;
        }
        var memento = this._mementos.Last();
        this._mementos.Remove(memento);
        Console.WriteLine("Caretaker: Restoring state to: " + memento.GetName());
        try
        {
            this._originator.Restore(memento);
        }
        catch (Exception)
        {
            this.Undo();
        }
    }
    public void ShowHistory()
    {
        Console.WriteLine("Caretaker: Here's the list of mementos:");
        foreach (var memento in this._mementos)
        {
            Console.WriteLine(memento.GetName());
        }
    }
}
Let's put this altogether in the main found in our Program.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
class Program
{  
    static void Main(string[] args)
    {
        Originator originator = new Originator("Super-duper-super-puper-super.");
        Caretaker caretaker = new Caretaker(originator);
        caretaker.Backup();
        originator.DoSomething();
        caretaker.Backup();
        originator.DoSomething();
        caretaker.Backup();
        originator.DoSomething();
        Console.WriteLine();
        caretaker.ShowHistory();
        Console.WriteLine("\nClient: Now, let's rollback!\n");
        caretaker.Undo();
        Console.WriteLine("\n\nClient: Once more!\n");
        caretaker.Undo();
        Console.WriteLine();
    }
}
And now we compile and run, we should have:
Originator: My initial state is: Super-duper-super-puper-super.

Caretaker: Saving Originator's state...
Originator: I'm doing something important.
Originator: and my state has changed to: FUbIPCClPpINblHPItNAyKBRfbbhWI

Caretaker: Saving Originator's state...
Originator: I'm doing something important.
Originator: and my state has changed to: MDreYrDtHOIrFyNXxvdWhmmOqGfWoA

Caretaker: Saving Originator's state...
Originator: I'm doing something important.
Originator: and my state has changed to: ngaSoRhJYcXaxKESQOPTprQMmlcpze

Caretaker: Here's the list of mementos:
5/29/2021 12:21:20 PM / (Super-dup)...
5/29/2021 12:21:21 PM / (FUbIPCClP)...
5/29/2021 12:21:21 PM / (MDreYrDtH)...

Client: Now, let's rollback!

Caretaker: Restoring state to: 5/29/2021 12:21:21 PM / (MDreYrDtH)...
Originator: My state has changed to: MDreYrDtHOIrFyNXxvdWhmmOqGfWoA

Client: Once more!

Caretaker: Restoring state to: 5/29/2021 12:21:21 PM / (FUbIPCClP)...
Originator: My state has changed to: FUbIPCClPpINblHPItNAyKBRfbbh
The Ray Code is AWESOME!!!
Find Ray on:

wikipedia
facebook
youtube
The Ray Code
Ray Andrade

Friday, May 28, 2021

Memento pattern c++

Memento is a behavioral design pattern that allows making snapshots of an object’s state and restoring it in future. The Memento’s principle can be achieved using the serialization, which is quite common in C++.
We start with createing a class we call the Memento The Memento interface provides a way to retrieve the memento's metadata, such as creation date or name. However, it doesn't expose the Originator's state.
#include <iostream>

class Memento {
public:
    virtual std::string GetName() const = 0;
    virtual std::string date() const = 0;
    virtual std::string state() const = 0;

};
The SolverMemento contains the infrastructure for storing the Originator's state.
#include 
#include "Memento.h"

class SolverMemento : public Memento {
private:
    std::string state_;
    std::string date_;
public:
    SolverMemento(std::string state) : state_(state) {
        this->state_ = state;
        std::time_t now = std::time(0);
        this->date_ = std::ctime(&now);
    }
    std::string state() const override {
        return this->state_;
    }
    std::string GetName() const override {
        return this->date_ + " / (" + this->state_.substr(0, 9) + "...)";
    }
    std::string date() const override {
        return this->date_;
    }
};
The Originator's business logic may affect its internal state. Therefore, the client should backup the state before launching methods of the business logic via the save() method. And then Saves the current state inside a memento. It also Restores the Originator's state from a memento object.
#include <iostream>
#include "Memento.h"
#include "SolverMemento.h"

class Originator {
private:
    std::string state_;
    std::string GenerateRandomString(int length = 10) {
        const char alphanum[] =
                "0123456789"
                "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                "abcdefghijklmnopqrstuvwxyz";
        int stringLength = sizeof(alphanum) - 1;
        std::string random_string;
        for (int i = 0; i < length; i++) {
            random_string += alphanum[std::rand() % stringLength];
        }
        return random_string;
    }
public:
    Originator(std::string state) : state_(state) {
        std::cout << "Originator: My initial state is: " << this->state_ << "\n";
    }
    void DoSomething() {
        std::cout << "Originator: I'm doing something important.\n";
        this->state_ = this->GenerateRandomString(30);
        std::cout << "Originator: and my state has changed to: " << this->state_ << "\n";
    }
    Memento *Save() {
        return new SolverMemento(this->state_);
    }
    /**
     * Restores the Originator's state from a memento object.
     */
    void Restore(Memento *memento) {
        this->state_ = memento->state();
        std::cout << "Originator: My state has changed to: " << this->state_ << "\n";
    }
};


The Caretaker doesn't depend on the Concrete Memento class. Therefore, it doesn't have access to the originator's state, stored inside the memento. It works with all mementos via the base Memento interface.
#include <iostream>
//#include <string>
#include <ctime>
#include <vector>
#include "Memento.h"
#include "Originator.h"

class Caretaker {
private:
    std::vector<Memento *> mementos_;
    Originator *originator_;
public:
    Caretaker(Originator *originator) : originator_(originator) {
        this->originator_ = originator;
    }
    void Backup() {
        std::cout << "\nCaretaker: Saving Originator's state...\n";
        this->mementos_.push_back(this->originator_->Save());
    }
    void Undo() {
        if (!this->mementos_.size()) {
            return;
        }
        Memento *memento = this->mementos_.back();
        this->mementos_.pop_back();
        std::cout << "Caretaker: Restoring state to: " << memento->GetName() << "\n";
        try {
            this->originator_->Restore(memento);
        } catch (...) {
            this->Undo();
        }
    }
    void ShowHistory() const {
        std::cout << "Caretaker: Here's the list of mementos:\n";
        for (Memento *memento : this->mementos_) {
            std::cout << memento->GetName() << "\n";
        }
    }
};
Let's put tis together in the ClientCode, afunction we place in the main.cpp.
void ClientCode() {
    Originator *originator = new Originator("Super-duper-super-puper-super.");
    Caretaker *caretaker = new Caretaker(originator);
    caretaker->Backup();
    originator->DoSomething();
    caretaker->Backup();
    originator->DoSomething();
    caretaker->Backup();
    originator->DoSomething();
    std::cout << "\n";
    caretaker->ShowHistory();
    std::cout << "\nClient: Now, let's rollback!\n\n";
    caretaker->Undo();
    std::cout << "\nClient: Once more!\n\n";
    caretaker->Undo();

    delete originator;
    delete caretaker;
}
.. And we execute the function in the main method
int main() {
    std::srand(static_cast<unsigned int>(std::time(NULL)));
    ClientCode();
    return 0;
}
When we compile and run we should get:
Originator: My initial state is: Super-duper-super-puper-super.

Caretaker: Saving Originator's state...
Originator: I'm doing something important.
Originator: and my state has changed to: j01MCvKXlnNu6gpdpQQA0SaNouXfJm

Caretaker: Saving Originator's state...
Originator: I'm doing something important.
Originator: and my state has changed to: h0mhMwceTLQqDWV29KRYSP02nmuIRD

Caretaker: Saving Originator's state...
Originator: I'm doing something important.
Originator: and my state has changed to: 57BpmVmM8DgY2t4XuCpLkHiiHTUCmu

Caretaker: Here's the list of mementos:
Thu May 27 15:19:41 2021
 / (Super-dup...)
Thu May 27 15:19:41 2021
 / (j01MCvKXl...)
Thu May 27 15:19:41 2021
 / (h0mhMwceT...)

Client: Now, let's rollback!

Caretaker: Restoring state to: Thu May 27 15:19:41 2021
 / (h0mhMwceT...)
Originator: My state has changed to: h0mhMwceTLQqDWV29KRYSP02nmuIRD

Client: Once more!

Caretaker: Restoring state to: Thu May 27 15:19:41 2021
 / (j01MCvKXl...)
Originator: My state has changed to: j01MCvKXlnNu6gpdpQQA0SaNouXfJm
The Ray Code is AWESOME!!!
Find Ray on:

wikipedia
facebook
youtube
The Ray Code
Ray Andrade

Thursday, May 27, 2021

Mediator pattern php

Mediator is a behavioral design pattern that lets you reduce chaotic dependencies between objects. The pattern restricts direct communications between the objects and forces them to collaborate only via a mediator object.
The pure implementation of the Mediator pattern isn’t as common in PHP, as it’s in other languages, especially GUI-targeted like Java or C#. A PHP application may indeed contain dozens of components, but they rarely communicate directly within a single session.
We start by createing the Mediator interface
The Mediator interface declares a method used by components to notify the mediator about various events. The Mediator may react to these events and pass the execution to other components.
interface Mediator
{
    public function notify(object $sender, string $event): void;
}

The Base Component provides the basic functionality of storing a mediator's instance inside component objects.
class BaseComponent
{
    protected $mediator;

    public function __construct(Mediator $mediator = null)
    {
        $this->mediator = $mediator;
    }
    public function setMediator(Mediator $mediator): void
    {
        $this->mediator = $mediator;
    }
}

Solid Mediators implement cooperative behavior by coordinating several components.
class SolidMediator implements Mediator
{
    private $componentA;
    private $componentB;
    public function __construct(ComponentA $cA, ComponentB $cB)
    {
        $this->componentA = $cA;
        $this->componentA->setMediator($this);
        $this->componentB = $cB;
        $this->componentB->setMediator($this);
    }
    public function notify(object $sender, string $event): void
    {
        if ($event == "A") {
            echo "Mediator reacts on A and triggers following operations:<br/>";
            $this->componentB->doC();
        }

        if ($event == "D") {
            echo "Mediator reacts on D and triggers following operations:<br/>";
            $this->componentA->doB();
            $this->componentB->doC();
        }
    }
}


Concrete Components implement various functionality. They don't depend on other components. They also don't depend on any concrete mediator classes.
class ComponentA extends BaseComponent
{
    public function doA(): void
    {
        echo "Component A does A.<br/>";
        $this->mediator->notify($this, "A");
    }
    public function doB(): void
    {
        echo "Component B does B.<br/>";
        $this->mediator->notify($this, "B");
    }
}

Let's create another component we call ComponentB
class ComponentB extends BaseComponent
{
    public function doC(): void
    {
        echo "Component A does C.<br/>";
        $this->mediator->notify($this, "C");
    }
    public function doD(): void
    {
        echo "Component B does D.<br/>";
        $this->mediator->notify($this, "D");
    }
}

Let's put this altogether in the index.php we first need to have our includes at the top.
include_once ('Mediator.php');
include_once('SolidMediator.php');
include_once ('BaseComponent.php');
include_once('ComponentA.php');
include_once('ComponentB.php');

Now the rest of the demo
$cA = new ComponentA;
$cB = new ComponentB;
$mediator = new SolidMediator($cA, $cB);

echo "Client triggers operation A.<br/>";
$cA->doA();

echo "
"; echo "Client triggers operation B.<br/>"; $cB->doD();

When we veiw our php code thru a browser we should get
Client triggers operation A.
Component A does A.
Mediator reacts on A and triggers following operations:
Component A does C.

Client triggers operation B.
Component B does D.
Mediator reacts on D and triggers following operations:
Component B does B.
Component A does C.
The Ray Code is AWESOME!!!
Find Ray on:

wikipedia
facebook
youtube
The Ray Code
Ray Andrade

Wednesday, May 26, 2021

Mediator pattern java

We start by createing an *interface* in which we call the Mediator.
public interface Mediator {
    public void saleOffer(String stock, int shares, int collCode);
    public void buyOffer(String stock, int shares, int collCode);
    public void addColleague(Colleague colleague);
}
We also want to create an abstract class called the Colleague.
public abstract class Colleague {
    private Mediator mediator;
    private int colleagueCode;
    public Colleague(Mediator newMediator){
        mediator = newMediator;
        mediator.addColleague(this);
    }
    public void saleOffer(String stock, int shares){
        mediator.saleOffer(stock, shares, this.colleagueCode);
    }
    public void buyOffer(String stock, int shares){
        mediator.buyOffer(stock, shares, this.colleagueCode);
    }
    public void setCollCode(int collCode){ colleagueCode = collCode; }
}
Let's now create a class that will be the **StockMediator**.
import java.util.ArrayList;

public class StockMediator implements Mediator{
    private ArrayList<Colleague> colleagues;
    private ArrayList<StockOffer> stockBuyOffers;
    private ArrayList<StockOffer> stockSaleOffers;
    private int colleagueCodes = 0;
    public StockMediator(){
        colleagues = new ArrayList<Colleague>();
        stockBuyOffers = new ArrayList<StockOffer>();
        stockSaleOffers = new ArrayList<StockOffer>();
    }
    public void addColleague(Colleague newColleague){
        colleagues.add(newColleague);
        colleagueCodes++;
        newColleague.setCollCode(colleagueCodes);
    }
    public void saleOffer(String stock, int shares, int collCode) {
        boolean stockSold = false;
        for(StockOffer offer: stockBuyOffers){
            if((offer.getStockSymbol() == stock) && (offer.getstockShares() == shares)){
                System.out.println(shares + " shares of " + stock +
                        " sold to colleague code " + offer.getCollCode());
                stockBuyOffers.remove(offer);
                stockSold = true;
            }
            if(stockSold){ break; }
        }
        if(!stockSold) {
            System.out.println(shares + " shares of " + stock +
                    " added to inventory");
            StockOffer newOffering = new StockOffer(shares, stock, collCode);
            stockSaleOffers.add(newOffering);
        }
    }
    @Override
    public void buyOffer(String stock, int shares, int collCode) {
        boolean stockBought = false;
        for(StockOffer offer: stockSaleOffers){
            if((offer.getStockSymbol() == stock) && (offer.getstockShares() == shares)){
                System.out.println(shares + " shares of " + stock +
                        " bought by colleague code " + offer.getCollCode());
                stockSaleOffers.remove(offer);
                stockBought = true;
            }
            if(stockBought){ break; }
        }
        if(!stockBought) {
            System.out.println(shares + " shares of " + stock +
                    " added to inventory");
            StockOffer newOffering = new StockOffer(shares, stock, collCode);
            stockBuyOffers.add(newOffering);
        }
    }
    public void getstockOfferings(){
        System.out.println("\nStocks for Sale");
        for(StockOffer offer: stockSaleOffers){
            System.out.println(offer.getstockShares() + " of " + offer.getStockSymbol());
        }
        System.out.println("\nStock Buy Offers");
        for(StockOffer offer: stockBuyOffers){
            System.out.println(offer.getstockShares() + " of " + offer.getStockSymbol());
        }
    }
}


Now let's create a class we call StockOffer.
public class StockOffer {
    private int stockShares = 0;
    private String stockSymbol = "";
    private int colleagueCode = 0;
    public StockOffer(int numOfShares, String stock, int collCode){

        stockShares = numOfShares;
        stockSymbol = stock;
        colleagueCode = collCode;

    }

    public int getstockShares() { return stockShares; }
    public String getStockSymbol() { return stockSymbol; }
    public int getCollCode() { return colleagueCode; }
}
Now let's create another stock offering classes we call **GormanSlacks**.
public class GormanSlacks extends Colleague{
    public GormanSlacks(Mediator newMediator) {
        super(newMediator);
        System.out.println("Gorman Slacks signed up with the stockexchange\n");
    }
}
Let's create another stock offering classes we call **JTPoorman**.
public class JTPoorman extends Colleague{
    public JTPoorman(Mediator newMediator) {
        super(newMediator);
        System.out.println("JT Poorman signed up with the stockexchange\n");
    }
}
Let's put tis all togeher in a main method.
public class TestStockMediator {
    public static void main(String[] args){
        StockMediator nyse = new StockMediator();
        GormanSlacks broker = new GormanSlacks(nyse);
        JTPoorman broker2 = new JTPoorman(nyse);
        broker.saleOffer("MSFT", 100);
        broker.saleOffer("GOOG", 50);
        broker2.buyOffer("MSFT", 100);
        broker2.saleOffer("NRG", 10);
        broker.buyOffer("NRG", 10);
        nyse.getstockOfferings();
    }
}
When we compile an run we should have,
Gorman Slacks signed up with the stockexchange

JT Poorman signed up with the stockexchange

100 shares of MSFT added to inventory
50 shares of GOOG added to inventory
100 shares of MSFT bought by colleague code 1
10 shares of NRG added to inventory
10 shares of NRG bought by colleague code 2

Stocks for Sale
50 of GOOG

Stock Buy Offers
The Ray Code is AWESOME!!!
Find Ray on:

wikipedia
facebook
youtube
The Ray Code
Ray Andrade

Tuesday, May 25, 2021

Mediator pattern c#

We start with the Mediator interface. The Mediator interface declares a method used by components to notify the mediator about various events. The Mediator may react to these events and pass the execution to other components.
public interface Mediator
{
   void Notify(object sender, string ev);
}
Let's extend a class we call the ConcreteMediator with the Mediator interface. Concrete Mediators implement cooperative behavior by coordinating several components.
class ConcreteMediator : Mediator
{
    private ConcreateColleage1 _concreateColleage1;
    private ConcreateColleage2 _concreateColleage2;
    public ConcreteMediator(ConcreateColleage1 concreateColleage1, ConcreateColleage2 concreateColleage2)
    {
        this._concreateColleage1 = concreateColleage1;
        this._concreateColleage1.SetMediator(this);
        this._concreateColleage2 = concreateColleage2;
        this._concreateColleage2.SetMediator(this);
    } 
    public void Notify(object sender, string ev)
    {
        if (ev == "A")
        {
            Console.WriteLine("Mediator reacts on A and triggers folowing operations:");
            this._concreateColleage2.DoC();
        }
        if (ev == "D")
        {
            Console.WriteLine("Mediator reacts on D and triggers following operations:");
            this._concreateColleage1.DoB();
            this._concreateColleage2.DoC();
        }
    }
}


We first create a base componet for our Concreate Colleageies. The code for our interface is:
class BaseComponent
{
    protected Mediator _mediator;
    public BaseComponent(Mediator mediator = null)
    {
         this._mediator = mediator;
    }
    public void SetMediator(Mediator mediator)
    {
        this._mediator = mediator;
    }
}
Let's now add these Concreate Colleageies classes to our project. For our first class ConcreateColleage1 the code will be: Concrete Colleageies implement various functionality. They don't depend on other components. They also don't depend on any concrete mediator classes.
class ConcreateColleage1 : BaseComponent
{
    public void DoA()
    {
        Console.WriteLine("Colleage 1 does A.");
        this._mediator.Notify(this, "A");
    }
    public void DoB()
    {
        Console.WriteLine("Colleage 1 does B.");
        this._mediator.Notify(this, "B");
    }
}
Let's create a second class we call the ConcreateColleage2 that is also extended with the BaseComponent class.
class ConcreateColleage2 : BaseComponent
{
    public void DoC()
    {
        Console.WriteLine("Colleage 2 does C.");
        this._mediator.Notify(this, "C");
    }
    public void DoD()
    {
        Console.WriteLine("Colleage 2 does D.");
        this._mediator.Notify(this, "D");
    }
}
Let's go to the Program.cs file. The client code.
static void Main(string[] args)
{
    ConcreateColleage1 concreateColleage1 = new ConcreateColleage1();
    ConcreateColleage2 concreateColleage2 = new ConcreateColleage2();
    new ConcreteMediator(concreateColleage1, concreateColleage2);

    Console.WriteLine("Client triggets operation A.");
    concreateColleage1.DoA();

    Console.WriteLine();
    Console.WriteLine("Client triggers operation D.");
    concreateColleage2.DoD();
    }
}
Let's compile this and then run, we should get:
Client triggets operation A.
Colleage 1 does A.
Mediator reacts on A and triggers folowing operations:
Colleage 2 does C.

Client triggers operation D.
Colleage 2 does D.
Mediator reacts on D and triggers following operations:
Colleage 1 does B.
Colleage 2 does C.
The Ray Code is AWESOME!!!
Find Ray on:

wikipedia
facebook
youtube
The Ray Code
Ray Andrade

Monday, May 24, 2021

Mediator pattern c++

The most popular usage of the Mediator pattern in C++ code is facilitating communications between GUI components of an app. The synonym of the Mediator is the Controller part of MVC pattern. We create a class we call the Mediator. The Mediator interface declares a method used by components to notify the mediator about various events. The Mediator may react to these events and pass the execution to other components.
#include <string>

class BaseComponent;
class Mediator {
public:
    virtual void Notify(BaseComponent *sender, std::string event) const = 0;
};
So let's create our **BaseComponent**
#include <string>

class BaseComponent;
class Mediator {
public:
    virtual void Notify(BaseComponent *sender, std::string event) const = 0;
};
Concrete Components implement various functionality. They don't depend on other components. They also don't depend on any concrete mediator classes. Let's create a couple of Components. We will name the FirstComponent and SecondComponent. Let's start with the FirstComponent.
#include <iostream>
#include "BaseComponent.h"

class FirstComponent : public BaseComponent {
public:
    void DoAction() {
        std::cout << "The First Component does Action.\n";
        this->mediator_->Notify(this, "Action");
    }
    void DoB() {
        std::cout << "The First Component does B.\n";
        this->mediator_->Notify(this, "B");
    }
};


Let create the SecondComponent. It's code will be:
#include <iostream>
#include "BaseComponent.h"

class SecondComponent : public BaseComponent  {
public:
    void DoC() {
        std::cout << "The Second Component does C.\n";
        this->mediator_->Notify(this, "C");
    }
    void DoD() {
        std::cout << "The Second Component does Deed.\n";
        this->mediator_->Notify(this, "D");
    }
};
We also need a ConcreteMediator.
#include "FirstComponent.h"
#include "SecondComponent.h"
class ConcreteMediator : public Mediator   {
private:
    FirstComponent *component1_;
    SecondComponent *component2_;
public:
    ConcreteMediator(FirstComponent *c1, SecondComponent *c2) : component1_(c1), component2_(c2) {
        this->component1_->set_mediator(this);
        this->component2_->set_mediator(this);
    }
    void Notify(BaseComponent *sender, std::string event) const override {
        if (event == "A") {
            std::cout << "Mediator reacts on A and triggers following operations:\n";
            this->component2_->DoC();
        }
        if (event == "D") {
            std::cout << "Mediator reacts on the Deed and triggers following operations:\n";
            this->component1_->DoB();
            this->component2_->DoC();
        }
    }
};
and lasly we go to the main.cpp and add some client code.
#include "ConcreteMediator.h"

void ClientCode() {
    FirstComponent *c1 = new FirstComponent;
    SecondComponent *c2 = new SecondComponent;
    ConcreteMediator *mediator = new ConcreteMediator(c1, c2);
    std::cout << "Client triggers operation A.\n";
    c1->DoAction();
    std::cout << "\n";
    std::cout << "Client triggers operation D.\n";
    c2->DoD();

    delete c1;
    delete c2;
    delete mediator;
}
Lastly we put the ClientCode in the main method...
int main() {
    ClientCode();
    return 0;
}
We then compile and run we should get:
Client triggers operation A.
The First Component does Action.

Client triggers operation D.
The Second Component does Deed.
Mediator reacts on the Deed and triggers following operations:
The First Component does B.
The Second Component does C.
The Ray Code is AWESOME!!!
Find Ray on:

wikipedia
facebook
youtube
The Ray Code
Ray Andrade

Saturday, May 22, 2021

Iterator pattern php

The Iterator design patterns is a behavioral design pattern that lets you traverse elements of a collection without exposing its underlying representation (list, stack, tree, etc.). Concrete Iterators implement various traversal algorithms. These classes store the current traversal position at all times. Stores the current traversal position. An iterator may have a lot of other fields for storing iteration state, especially when it is supposed to work with a particular kind of collection.
 class AlphabeticalOrderIterator implements \Iterator
{
    private $collection;
    private $position = 0;
    private $reverse = false;
    public function __construct($collection, $reverse = false)
    {
        $this->collection = $collection;
        $this->reverse = $reverse;
    }
    public function rewind()
    {
        $this->position = $this->reverse ?
            count($this->collection->getItems()) - 1 : 0;
    }
    public function current()
    {
        return $this->collection->getItems()[$this->position];
    }
    public function key()
    {
        return $this->position;
    }
    public function next()
    {
        $this->position = $this->position + ($this->reverse ? -1 : 1);
    }
    public function valid()
    {
        return isset($this->collection->getItems()[$this->position]);
    }
}
![Iterator](/UMLs/images/Iterator/Iterator-4.png) Concrete Collections provide one or several methods for retrieving fresh iterator instances, compatible with the collection class.
class WordsCollection implements \IteratorAggregate
{
    private $items = [];
    public function getItems()
    {
        return $this->items;
    }
    public function addItem($item)
    {
        $this->items[] = $item;
    }
    public function getIterator(): Iterator
    {
        return new AlphabeticalOrderIterator($this);
    }
    public function getReverseIterator(): Iterator
    {
        return new AlphabeticalOrderIterator($this, true);
    }
}
The client code may or may not know about the Concrete Iterator or Collection classes, depending on the level of indirection you want to keep in your program.
include_once ('AlphabeticalOrderIterator.php');
include_once ('WordsCollection.php');

$collection = new WordsCollection;
$collection->addItem("A");
$collection->addItem("B");
$collection->addItem("C");

echo "Straight traversal:<br/>";
foreach ($collection->getIterator() as $item) {
    echo $item . "<br/>";
}

echo "
"; echo "Reverse traversal:<br/>"; foreach ($collection->getReverseIterator() as $item) { echo $item . "<br/>";
When we veiw this through a browser we get:
Straight traversal:
A
B
C

Reverse traversal:
C
B
A
The Ray Code is AWESOME!!!
Find Ray on:

wikipedia
facebook
youtube
The Ray Code
Ray Andrade

Friday, May 21, 2021

Iterator pattern java

We start by creating a package we called profile (TheRayCode.iterator.profile ) To this package we add the class Profile. We parse the contact list from a set of "friend:email@gmail.com" pairs.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Profile {
    private String name;
    private String email;
    private Map<String, List<String>> contacts = new HashMap<>();

    public Profile(String email, String name, String... contacts) {
        this.email = email;
        this.name = name;
        for (String contact : contacts) {
            String[] parts = contact.split(":");
            String contactType = "friend", contactEmail;
            if (parts.length == 1) {
                contactEmail = parts[0];
            }
            else {
                contactType = parts[0];
                contactEmail = parts[1];
            }
            if (!this.contacts.containsKey(contactType)) {
                this.contacts.put(contactType, new ArrayList<>());
            }
            this.contacts.get(contactType).add(contactEmail);
        }
    }
    public String getEmail() {
        return email;
    }
    public String getName() {
        return name;
    }
    public List<String> getContacts(String contactType) {
        if (!this.contacts.containsKey(contactType)) {
            this.contacts.put(contactType, new ArrayList<>());
        }
        return contacts.get(contactType);
    }
}


We add another package we call iterators. To this package we add the interface called ProfileIterator.
public interface ProfileIterator {
    boolean hasNext();
    Profile getNext();
    void reset();
}
Let's add a class to this package we call the FacebookIterator it will be implmented by the intertface ProfileIterator.
import TheRayCode.iterator.profile.Profile;
import TheRayCode.iterator.social_networks.Facebook;

import java.util.ArrayList;
import java.util.List;

public class FacebookIterator implements ProfileIterator {
    private Facebook facebook;
    private String type;
    private String email;
    private int currentPosition = 0;
    private List<String> emails = new ArrayList<>();
    private List<Profile> profiles = new ArrayList<>();

    public FacebookIterator(Facebook facebook, String type, String email) {
        this.facebook = facebook;
        this.type = type;
        this.email = email;
    }

    private void lazyLoad() {
        if (emails.size() == 0) {
            List<String> profiles = facebook.requestProfileFriendsFromFacebook(this.email, this.type);
            for (String profile : profiles) {
                this.emails.add(profile);
                this.profiles.add(null);
            }
        }
    }

    @Override
    public boolean hasNext() {
        lazyLoad();
        return currentPosition < emails.size();
    }

    @Override
    public Profile getNext() {
        if (!hasNext()) {
            return null;
        }

        String friendEmail = emails.get(currentPosition);
        Profile friendProfile = profiles.get(currentPosition);
        if (friendProfile == null) {
            friendProfile = facebook.requestProfileFromFacebook(friendEmail);
            profiles.set(currentPosition, friendProfile);
        }
        currentPosition++;
        return friendProfile;
    }

    @Override
    public void reset() {
        currentPosition = 0;
    }
}
We create another iterator class called the LinkedInIterator. It too is implemented with the ProfileIterator.
import TheRayCode.iterator.profile.Profile;
import TheRayCode.iterator.social_networks.LinkedIn;

import java.util.ArrayList;
import java.util.List;

public class LinkedInIterator implements ProfileIterator {
    private LinkedIn linkedIn;
    private String type;
    private String email;
    private int currentPosition = 0;
    private List<String> emails = new ArrayList<>();
    private List<Profile> contacts = new ArrayList<>();

    public LinkedInIterator(LinkedIn twitter, String type, String email) {
        this.linkedIn = twitter;
        this.type = type;
        this.email = email;
    }

    private void lazyLoad() {
        if (emails.size() == 0) {
            List<String> profiles = linkedIn.requestRelatedContactsFromLinkedIn(this.email, this.type);
            for (String profile : profiles) {
                this.emails.add(profile);
                this.contacts.add(null);
            }
        }
    }

    @Override
    public boolean hasNext() {
        lazyLoad();
        return currentPosition < emails.size();
    }

    @Override
    public Profile getNext() {
        if (!hasNext()) {
            return null;
        }

        String friendEmail = emails.get(currentPosition);
        Profile friendContact = contacts.get(currentPosition);
        if (friendContact == null) {
            friendContact = linkedIn.requestContactInfoFromLinkedIn(friendEmail);
            contacts.set(currentPosition, friendContact);
        }
        currentPosition++;
        return friendContact;
    }

    @Override
    public void reset() {
        currentPosition = 0;
    }
}
We create a package we call social_networks. To this package we add the interface we call **SocialNetwork**.
import TheRayCode.iterator.iterators.ProfileIterator;

public interface SocialNetwork {
    ProfileIterator createFriendsIterator(String profileEmail);
    ProfileIterator createCoworkersIterator(String profileEmail);
}
Next we add the class for Facebook. In the method requestProfileFriendsFromFacebook we POST a request to one of the Facebook API endpoints. Instead, we emulates long network connection, which you would expect in the real life and return test data.
import TheRayCode.iterator.iterators.FacebookIterator;
import TheRayCode.iterator.iterators.ProfileIterator;
import TheRayCode.iterator.profile.Profile;

import java.util.ArrayList;
import java.util.List;

public class Facebook implements SocialNetwork {
    private List<Profile> profiles;
    public Facebook(List<Profile> cache) {
        if (cache != null) {
            this.profiles = cache;
        } else {
            this.profiles = new ArrayList<>();
        }
    }
    public Profile requestProfileFromFacebook(String profileEmail) {
        simulateNetworkLatency();
        System.out.println("Facebook: Loading profile '" + profileEmail + "' over the network...");
        return findProfile(profileEmail);
    }

    public List<String> requestProfileFriendsFromFacebook(String profileEmail, String contactType) {
        simulateNetworkLatency();
        System.out.println("Facebook: Loading '" + contactType + "' list of '" + profileEmail + "' over the network...");
        Profile profile = findProfile(profileEmail);
        if (profile != null) {
            return profile.getContacts(contactType);
        }
        return null;
    }

    private Profile findProfile(String profileEmail) {
        for (Profile profile : profiles) {
            if (profile.getEmail().equals(profileEmail)) {
                return profile;
            }
        }
        return null;
    }

    private void simulateNetworkLatency() {
        try {
            Thread.sleep(2500);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public ProfileIterator createFriendsIterator(String profileEmail) {
        return new FacebookIterator(this, "friends", profileEmail);
    }

    @Override
    public ProfileIterator createCoworkersIterator(String profileEmail) {
        return new FacebookIterator(this, "coworkers", profileEmail);
    }

}
We also add a class for LinkedIn called LinkedIn. It too is implemented with the SocialNetwork interface. The Profile requestContactInfoFromLinkedIn method would be a POST request to one of the LinkedIn API endpoints. Instead, we emulates long network connection, which you would expect in the real life and return test data. The List<String> requestRelatedContactsFromLinkedIn method would be a POST request to one of the Titter API endpoints. Instead, we also emulate a long network connection, which you would expect in the real life and return test data
import TheRayCode.iterator.iterators.LinkedInIterator;
import TheRayCode.iterator.iterators.ProfileIterator;
import TheRayCode.iterator.profile.Profile;

import java.util.ArrayList;
import java.util.List;

public class LinkedIn implements SocialNetwork {
    private List<Profile> contacts;
    public LinkedIn(List<Profile> cache) {
        if (cache != null) {
            this.contacts = cache;
        } else {
            this.contacts = new ArrayList<>();
        }
    }
    public Profile requestContactInfoFromLinkedIn(String profileEmail) {
        simulateNetworkLatency();
        System.out.println("LinkedIn: Loading profile '" + profileEmail + "' over the network...");
        return findContact(profileEmail);
    }

    public List<String> requestRelatedContactsFromLinkedIn(String profileEmail, String contactType) {
        simulateNetworkLatency();
        System.out.println("LinkedIn: Loading '" + contactType + "' list of '" + profileEmail + "' over the network...");
        Profile profile = findContact(profileEmail);
        if (profile != null) {
            return profile.getContacts(contactType);
        }
        return null;
    }

    private Profile findContact(String profileEmail) {
        for (Profile profile : contacts) {
            if (profile.getEmail().equals(profileEmail)) {
                return profile;
            }
        }
        return null;
    }

    private void simulateNetworkLatency() {
        try {
            Thread.sleep(2500);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public ProfileIterator createFriendsIterator(String profileEmail) {
        return new LinkedInIterator(this, "friends", profileEmail);
    }

    @Override
    public ProfileIterator createCoworkersIterator(String profileEmail) {
        return new LinkedInIterator(this, "coworkers", profileEmail);
    }
}
Now let's create the SocialSpammer. We place it in a package we call TheRayCode.iterator.spammer.
import TheRayCode.iterator.example.iterators.ProfileIterator;
import TheRayCode.iterator.example.profile.Profile;
import TheRayCode.iterator.example.social_networks.SocialNetwork;

public class SocialSpammer {
    public SocialNetwork network;
    public ProfileIterator iterator;
    public SocialSpammer(SocialNetwork network) {
        this.network = network;
    }
    public void sendSpamToFriends(String profileEmail, String message) {
        System.out.println("\nIterating over friends...\n");
        iterator = network.createFriendsIterator(profileEmail);
        while (iterator.hasNext()) {
            Profile profile = iterator.getNext();
            sendMessage(profile.getEmail(), message);
        }
    }
    public void sendSpamToCoworkers(String profileEmail, String message) {
        System.out.println("\nIterating over coworkers...\n");
        iterator = network.createCoworkersIterator(profileEmail);
        while (iterator.hasNext()) {
            Profile profile = iterator.getNext();
            sendMessage(profile.getEmail(), message);
        }
    }
    public void sendMessage(String email, String message) {
        System.out.println("Sent message to: '" + email + "'. Message body: '" + message + "'");
    }
}
We put this all together in a class called **Demo**. Everything comes together here. The code for Demo is:
import TheRayCode.iterator.profile.Profile;
import TheRayCode.iterator.social_networks.Facebook;
import TheRayCode.iterator.social_networks.LinkedIn;
import TheRayCode.iterator.social_networks.SocialNetwork;
import TheRayCode.iterator.spammer.SocialSpammer;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Demo {
    public static Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) {
        System.out.println("Please specify social network to target spam tool (default:Facebook):");
        System.out.println("1. Facebook");
        System.out.println("2. LinkedIn");
        String choice = scanner.nextLine();
        SocialNetwork network;
        if (choice.equals("2")) {
            network = new LinkedIn(createTestProfiles());
        }
        else {
            network = new Facebook(createTestProfiles());
        }
        SocialSpammer spammer = new SocialSpammer(network);
        spammer.sendSpamToFriends("TheRayCode@RayAndrade.com",
                "Hey! This is Ray's friend Junk. Can you do me a favor and like this post TheRayCode.org?");
        spammer.sendSpamToCoworkers("TheRayCode@RayAndrade.com",
                "Hey! This is Ray's boss Support, Ray told me you would be interested in TheRayCode.org.");
    }
    public static List<Profile> createTestProfiles() {
        List<Profile> data = new ArrayList<Profile>();
        data.add(new Profile("TheRayCode@RayAndrade.com", "Ray Smith", "friends:mad_max@ya.com", "friends:catwoman@yahoo.com", "coworkers:sam@amazon.com"));
        data.add(new Profile("mad_max@ya.com", "Maximilian", "friends:TheRayCode@RayAndrade.com", "coworkers:sam@amazon.com"));
        data.add(new Profile("bill@microsoft.eu", "Billie", "coworkers:avanger@ukr.net"));
        data.add(new Profile("avanger@ukr.net", "John Day", "coworkers:bill@microsoft.eu"));
        data.add(new Profile("sam@amazon.com", "Sam Kitting", "coworkers:TheRayCode@RayAndrade.com", "coworkers:mad_max@ya.com", "friends:catwoman@yahoo.com"));
        data.add(new Profile("catwoman@yahoo.com", "Liza", "friends:TheRayCode@RayAndrade.com", "friends:sam@amazon.com"));
        return data;
    }
}
```

We now compile and run.
We should get:
Please specify social network to target spam tool (default:Facebook):
1. Facebook
2. LinkedIn
1

Iterating over friends...

Facebook: Loading 'friends' list of 'TheRayCode@RayAndrade.com' over the network...
Facebook: Loading profile 'mad_max@ya.com' over the network...
Sent message to: 'mad_max@ya.com'. Message body: 'Hey! This is Ray's friend Junk. Can you do me a favor and like this post TheRayCode.org?'
Facebook: Loading profile 'catwoman@yahoo.com' over the network...
Sent message to: 'catwoman@yahoo.com'. Message body: 'Hey! This is Ray's friend Junk. Can you do me a favor and like this post TheRayCode.org?'

Iterating over coworkers...

Facebook: Loading 'coworkers' list of 'TheRayCode@RayAndrade.com' over the network...
Facebook: Loading profile 'sam@amazon.com' over the network...
Sent message to: 'sam@amazon.com'. Message body: 'Hey! This is Ray's boss Support, Ray told me you would be interested in TheRayCode.org.'
When we select 2 we get
Iterating over friends...

LinkedIn: Loading 'friends' list of 'TheRayCode@RayAndrade.com' over the network...
LinkedIn: Loading profile 'mad_max@ya.com' over the network...
Sent message to: 'mad_max@ya.com'. Message body: 'Hey! This is Ray's friend Junk. Can you do me a favor and like this post TheRayCode.org?'
LinkedIn: Loading profile 'catwoman@yahoo.com' over the network...
Sent message to: 'catwoman@yahoo.com'. Message body: 'Hey! This is Ray's friend Junk. Can you do me a favor and like this post TheRayCode.org?'

Iterating over coworkers...

LinkedIn: Loading 'coworkers' list of 'TheRayCode@RayAndrade.com' over the network...
LinkedIn: Loading profile 'sam@amazon.com' over the network...
Sent message to: 'sam@amazon.com'. Message body: 'Hey! This is Ray's boss Support, Ray told me you would be interested in TheRayCode.org.'
The Ray Code is AWESOME!!!
Find Ray on:
wikipedia
facebook
youtube
The Ray Code
Ray Andrade

Thursday, May 20, 2021

Iterator pattern c#

The abstract key Returns the key of the current element. The Current object returns the current element. MoveNext moves forward to next element. Reset rewinds the Iterator to the first element.
abstract class Iterator : IEnumerator
{
    object IEnumerator.Current => Current();
    public abstract int Key();
    public abstract object Current();
    public abstract bool MoveNext();
    public abstract void Reset();
}
Returns an Iterator or another IteratorAggregate for the implementing object.
abstract class IteratorAggregate : IEnumerable
{
    public abstract IEnumerator GetEnumerator();
}
Concrete Iterators implement various traversal algorithms. These classes store the current traversal position at all times. The varables stores the current traversal position. An iterator may have a lot of other fields for storing iteration state, especially when it is supposed to work with a particular kind of collection.
class AlphabeticalOrderIterator : Iterator
{
    private WordsCollection _collection;
    private int _position = -1;
    private bool _reverse = false;
    public AlphabeticalOrderIterator(WordsCollection collection, bool reverse = false)
    {
        this._collection = collection;
        this._reverse = reverse;
        if (reverse)
        {
            this._position = collection.getItems().Count;
        }
    }
    public override object Current()
    {
        return this._collection.getItems()[_position];
    }
    public override int Key()
    {
        return this._position;
    }
    public override bool MoveNext()
    {
        int updatedPosition = this._position + (this._reverse ? -1 : 1);
        if (updatedPosition >= 0 && updatedPosition < this._collection.getItems().Count)
        {
            this._position = updatedPosition;
            return true;
        }
        else
        {
            return false;
        }
   }
   public override void Reset()
   {
        this._position = this._reverse ? this._collection.getItems().Count - 1 : 0;
   }
}


Concrete Collections provide one or several methods for retrieving fresh iterator instances, compatible with the collection class.
class WordsCollection : IteratorAggregate
{
    List<string> _collection = new List<string>();
    bool _direction = false;
    public void ReverseDirection()
    {
        _direction = !_direction;
    }
    public List<string> getItems()
    {
        return _collection;
    }
    public void AddItem(string item)
    {
        this._collection.Add(item);
    }
    public override IEnumerator GetEnumerator()
    {
        return new AlphabeticalOrderIterator(this, _direction);
    }
}
Let's put this all together in the Main method. The client code may or may not know about the Concrete Iterator or Collection classes, depending on the level of indirection you want to keep in your program.
static void Main(string[] args)
{
    var collection = new WordsCollection();
    collection.AddItem("A");
    collection.AddItem("B");
    collection.AddItem("C");
    Console.WriteLine("Forward traversal:");
    foreach (var element in collection)
    {
        Console.WriteLine(element);
    }
    Console.WriteLine("\nReverse traversal:");
    collection.ReverseDirection();
    foreach (var element in collection)
    {
        Console.WriteLine(element);
    }
}
Let's compile this and run. We should get:
Forward traversal:
A
B
C

Reverse traversal:
C
B
A
The Ray Code is AWESOME!!!
Find Ray on:

wikipedia
facebook
youtube
The Ray Code
Ray Andrade

Wednesday, May 19, 2021

Iterator pattern c++

C++ has its own implementation of iterator that works with a different generics containers defined by the standard library. We first create Template with < T, u>. We create a class called Iterator. The intorate will cycle our list.
template <typename T, typename U>
class Iterator {
public:
    typedef typename std::vector<T>::iterator iter_type;
    Iterator(U *p_data, bool reverse = false) : m_p_data_(p_data) {
        m_it_ = m_p_data_->m_data_.begin();
    }

    void First() {
        m_it_ = m_p_data_->m_data_.begin();
    }

    void Next() {
        m_it_++;
    }

    bool IsDone() {
        return (m_it_ == m_p_data_->m_data_.end());
    }

    iter_type Current() {
        return m_it_;
    }

private:
    U *m_p_data_;
    iter_type m_it_;
};
Generic Collections/Containers provides one or several methods for retrieving fresh iterator instances, compatible with the collection class.
#include "Iterator.h"
#include <vector>
template <class T>
class Container {
    friend class Iterator<T, Container>;

public:
    void Add(T a) {
        m_data_.push_back(a);
    }

    Iterator<T, Container> *CreateIterator() {
        return new Iterator<T, Container>(this);
    }

private:
    std::vector<T> m_data_;
};
We will create a class called Data.
class Data {
public:
    Data(int a = 0) : m_data_(a) {}

    void set_data(int a) {
        m_data_ = a;
    }

    int data() {
        return m_data_;
    }

private:
    int m_data_;
};
The client code may or may not know about the Concrete Iterator or Collection classes, for this implementation the container is generic so you can used with an int or with a custom class.
void ClientCode() {
    std::cout << "________________Iterator with int______________________________________" << std::endl;
    Container<int> cont;

    for (int i = 0; i < 10; i++) {
        cont.Add(i);
    }

    Iterator<int, Container<int>> *it = cont.CreateIterator();
    for (it->First(); !it->IsDone(); it->Next()) {
        std::cout << *it->Current() << std::endl;
    }

    Container<Data> cont2;
    Data a(100), b(1000), c(10000);
    cont2.Add(a);
    cont2.Add(b);
    cont2.Add(c);

    std::cout << "________________Iterator with custom Class______________________________" << std::endl;
    Iterator<Data, Container<Data>> *it2 = cont2.CreateIterator();
    for (it2->First(); !it2->IsDone(); it2->Next()) {
        std::cout << it2->Current()->data() << std::endl;
    }
}
We run the ClientCode in the main method.
int main() {
    ClientCode();
    return 0;
}
When we compile and run we get:
________________Iterator with int______________________________________
0
1
2
3
4
5
6
7
8
9
________________Iterator with custom Class______________________________
100
1000
10000
The Ray Code is AWESOME!!!
Find Ray on:

wikipedia
facebook
youtube
The Ray Code
Ray Andrade

Tuesday, May 18, 2021

Command pattern java

The command pattern is a behavioural design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time. This information includes the method name, the object that owns the method and values for the method parameters. Let's create an interface that will handle all of our receivers **ElectronicDevices**. We will add all the command ti proform.
public interface ElectronicDevice {
    public void on();
    public void off();
    public void volumeUp();
    public void volumenDown();
}
Let's make a reciever for Television. It will be extened by ElectronicDevice. Since it is extened by ElectronicDevice we need to add the required methods. We add a varable that hold the value of our volume. Let's also place some functionality in each of those methods.
public class Television implements ElectronicDevice {
    private int volume = 0;
    
    public void on() {
        System.out.println("TV is on");
    }

    public void off() {
        System.out.println("TV is off");
    }
    
    @Override
    public void volumeUp() {
        volume++;
        System.out.println("TV Volume is at: " + volume);
    }
    
    @Override
    public void volumenDown() {
        volume--;
        System.out.println("TV Volume is at: " + volume);
    }
}
We need to create an interface for our all commands to use called Command.
public interface Command {
    public void execute();
    // Added
    public void undo();
}
Next we will create the command to execute. Let's make a class that will turn on the TV called TurnTVOn.
public class TurnTVOn implements Command {
    ElectronicDevice theDevice;
    
    public TurnTVOn(ElectronicDevice newDevice){
        theDevice = newDevice;
    }
    
    @Override
    public void execute() {
        theDevice.on();
    }
    
    @Override // Added
    public void undo() {
        theDevice.off();
    }
}
We will also create a class to turn the TV off called TurnTVOff and of course it turns the TV off.
public class TurnTVOff implements Command {
    ElectronicDevice theDevice;
    
    public TurnTVOff(ElectronicDevice newDevice){
        theDevice = newDevice;
    }
    
    @Override
    public void execute() {
        theDevice.off();
    }

    // Used if you want to allow for undo
    // Do the opposite of execute()
    public void undo() {
        theDevice.on();
    }

}
Let's create a couple of specific commands that we can run through our interface.
public class TurnTVUp implements Command {
    ElectronicDevice theDevice;
    
    public TurnTVUp(ElectronicDevice newDevice){
        theDevice = newDevice;
    }
    
    @Override
    public void execute() {
        theDevice.volumeUp();
    }
    
    @Override
    public void undo() {
        theDevice.volumenDown();
    }
}
This is known as the invoker. It has a method press() that when executed causes the execute method to be called The execute method for the Command interface then calls the method assigned in the class that implements the Command interface.
public class DeviceButton{
    Command theCommand;
    
    public DeviceButton(Command newCommand){
        theCommand = newCommand;
    }
    
    public void press(){
        theCommand.execute();
    }
    // Now the remote can undo past commands
    public void pressUndo(){
        theCommand.undo();
    }
}
The purpose of TVRemote will be to return the type eletronic divice you are using.
public class TVRemote {
    public static ElectronicDevice getDevice(){
        return new Television();
    }
}
Gets the ElectronicDevice to use. TurnTVOn contains the command to turn on the tv When execute() is called on this command object it will execute the method on() in Television
import java.util.ArrayList;
import java.util.List;

public class PlayWithRemote {
    public static void main(String[] args){
        ElectronicDevice newDevice = TVRemote.getDevice();
        TurnTVOn onCommand = new TurnTVOn(newDevice);
Calling the execute() causes on() to execute in Television When press() is called theCommand.execute(); executes Calling the execute() causes off() to execute in Television Now when execute() is called volumeUp() of Television executes. Calling the execute() causes volumeUp() to execute in Television. When press() is called theCommand.execute(); executes. Creating a TV and Radio to turn off with 1 press.
        DeviceButton onPressed = new DeviceButton(onCommand);
        onPressed.press();
Now when execute() is called off() of Television executes
        
        TurnTVOff offCommand = new TurnTVOff(newDevice);
        onPressed = new DeviceButton(offCommand);
        onPressed.press();
Let work with **TurnTVUp**.
        TurnTVUp volUpCommand = new TurnTVUp(newDevice);
        onPressed = new DeviceButton(volUpCommand);
        onPressed.press();
        onPressed.press();
        onPressed.press();
        Television theTV = new Television();
Let's also work with the radio
        Radio theRadio = new Radio();

        // Add the Electronic Devices to a List
        List<ElectronicDevice> allDevices = new ArrayList<ElectronicDevice>();

        allDevices.add(theTV);
        allDevices.add(theRadio);
Send the List of Electronic Devices to TurnItAllOff where a call to run execute() on this function will call off() for each device in the list This calls for execute() to run which calls for off() to run for every ElectronicDevice
        TurnItAllOff turnOffDevices = new TurnItAllOff(allDevices);
        DeviceButton turnThemOff = new DeviceButton(turnOffDevices);
        turnThemOff.press();
It is common to be able to undo a command in a command pattern. To do so, DeviceButton will have a method called undo Undo() will perform the opposite action that the normal Command performs. undo() needs to be added to every class with an execute()
        turnThemOff.pressUndo();
    }
}
To undo more than one command add them to a LinkedList using addFirst(). Then execute undo on each item until there are none left. (This is your Homework)
import java.util.List;
public class TurnItAllOff implements Command {
    List<ElectronicDevice> theDevices;
    
    public TurnItAllOff(List<ElectronicDevice> newDevices) {
        theDevices = newDevices;
    }
    
    @Override
    public void execute() {
        for (ElectronicDevice device : theDevices) {
            device.off();
        }
    }
    
    @Override
    public void undo() {
        for (ElectronicDevice device : theDevices) {
            device.on();
        }
    }
}
Let's compile our program and run, we should get:
TV is on
TV is off
TV Volume is at: 1
TV Volume is at: 2
TV Volume is at: 3
TV is off
Radio is off
TV is on
Radio is on
The Ray Code is AWESOME!!!
Find Ray on:

wikipedia
facebook
youtube
The Ray Code
Ray Andrade

Monday, May 17, 2021

Command pattern php

Command is a behavioral design pattern that turns a request in a stand-alone object that contains the information needed for the request. This transformation lets you pass the requests as a method argument. The request cant be delaied, queued as a request’s execution. The request can also support undoable operations. This example will illustrate the structure of the Command design pattern and will focuses on the following questions:
  • What classes does it consist of?
  • What roles do these classes play?
  • In what way the elements of the pattern are related?
The Command interface declares a method for executing the command.
interface Command
{
    public function execute(): void;
}
Some commands can be implement with simple operations on their own. First, we will add a Simple Command that will implement the Command interface.
class SimpleCommand implements Command
{
    private $payload;

    public function __construct(string $payload)
    {
        $this->payload = $payload;
    }

    public function execute(): void
    {
        echo "SimpleCommand: does the request  (" . $this->payload . ")<br/>";
    }
}
Let's create a Complex Command. Now, some commands can delegate more complex operations to other objects. Those objects are called receivers. Some Context data will be required for launching the receiver's methods. Some Complex commands can accept one or more receiver objects along with any context data from the constructor. The Commands can delegate to any method of a receiver.
class ComplexCommand implements Command
{
    private $receiver;
    private $a;
    private $b;

    public function __construct(Receiver $receiver, string $a, string $b)
    {
        $this->receiver = $receiver;
        $this->a = $a;
        $this->b = $b;
    }

    public function execute(): void
    {
        echo "ComplexCommand: Complex stuff should be done by a receiver object.<br/>";
        $this->receiver->doSomething($this->a);
        $this->receiver->doSomethingElse($this->b);
    }
}


The Receiver classes contain some important business logic. They know how to perform all kinds of operations, associated with carrying out a request. In fact, any class may serve as a Receiver.
class Receiver
{
    public function doSomething(string $a): void
    {
        echo "Receiver: Working on (" . $a . ".)<br/>";
    }

    public function doSomethingElse(string $b): void
    {
        echo "Receiver: Also working on (" . $b . ".)<br/>";
    }
}
The Invoker is associated with one or several commands. It will send a request to the command. The Invoker does'nt depend on a concrete command or a receiver classes. The Invoker passes a request to a receiver indirectly, by executing it's command. At the top we place our includes:
include_once ('Command.php');
include_once ('SimpleCommand.php');
include_once ('ComplexCommand.php');
include_once ('Receiver.php');
include_once ('Invoker.php');
The client code can parameterize the invoker with any of the commands.
$invoker = new Invoker;
$invoker->setOnStart(new SimpleCommand("Say Hi!"));
$receiver = new Receiver;
$invoker->setOnFinish(new ComplexCommand($receiver, "Send email", "Save report"));
$invoker->doSomethingImportant();
When we when veiw our code through the browser we should get
Invoker: Makes a request
SimpleCommand: does the request (Say Hi!)
Invoker: does the action...
Invoker: Makes another request
ComplexCommand: Complex stuff should be done by a receiver object.
Receiver: Working on (Send email.)
Receiver: Also working on (Save report.)
The Ray Code is AWESOME!!!
Find Ray on:

wikipedia
facebook
youtube
The Ray Code
Ray Andrade

Saturday, May 15, 2021

Command pattern c#

Command is a behavioral design pattern that turns a request into a stand-alone object that contains all information about the request. This transformation lets you pass requests as a method arguments, delay or queue a request’s execution, and support undoable operations. The Command interface declares a method for executing a command.
public interface ICommand
{
    void Execute();
}
Some commands can implement simple operations on their own.
public class SimpleCmd : ICommand
{
    private readonly string _payload;
    public SimpleCmd(string payload)
    {
        this._payload = payload;
    }
    public void Execute()
    {
        Console.WriteLine($"A Simple Command: payload ({this._payload})");
    }
}
However, some commands can delegate more complex operations to other objects, called "receivers. Context data, required for launching the receiver's methods. Complex commands can accept one or several receiver objects along with any context data via the constructor.
public class ComplexCmd: ICommand
{
    private Receiver _receiver;

    private string _a;

    private string _b;

    public ComplexCmd(Receiver receiver, string a, string b)
    {
        this._receiver = receiver ?? throw new ArgumentNullException(nameof(receiver));
        this._a = a;
        this._b = b;
    }

    public void Execute()
    {
        Console.WriteLine("ComplexCommand Executed");
        this._receiver.DoSomething(this._a);
        this._receiver.DoSomethingElse(this._b);
    }
}


The Invoker is associated with one or several commands. It sends a request to the command. Initialize commands. The Invoker does not depend on concrete command or receiver classes. The Invoker passes a request to a receiver indirectly, by executing a command.
internal class Invoker
{
    private ICommand _onStart;
    private ICommand _onFinish;

    public void SetOnStart(ICommand command)
    {
        this._onStart = command;
    }

    public void SetOnFinish(ICommand command)
    {
        this._onFinish = command;
    }
        
    public void DoSomethingImportant()
    {
        Console.WriteLine("Invoker: Make a request");
        _onStart?.Execute();
        Console.WriteLine("Invoker: ...doing something really important...");
        Console.WriteLine("Invoker: Does anybody want something done after I finish?");
        _onFinish?.Execute();
    }
}
The Receiver classes contain some important business logic. They know how to perform all kinds of operations, associated with carrying out a request. In fact, any class may serve as a Receiver.
public class Receiver
{
    public void DoSomething(string a)
    {
        Console.WriteLine($"Receiver: Relieved first item ({a}.)");
    }

    public void DoSomethingElse(string b)
    {
        Console.WriteLine($"Receiver: Received Second Item ({b}.)");
    }
}
The client code can parameterize an invoker with any commands.
class Program
{
    static void Main(string[] args)
    {
        Invoker invoker = new Invoker();
        invoker.SetOnStart(new SimpleCmd("Command Start"));
        Receiver receiver = new Receiver();
        invoker.SetOnFinish(new ComplexCmd(receiver, "Do Stuff", "Do Complex Command"));
        invoker.DoSomethingImportant();
    }
}
Let's compile this and run. We should get:
Invoker: Make a request
A Simple Command: payload (Command Start)
Invoker: ...doing something really important...
Invoker: Does anybody want something done after I finish?
ComplexCommand Executed
Receiver: Relieved first item (Do Stuff.)
Receiver: Received Second Item (Do Complex Command.)
The Ray Code is AWESOME!!!
Find Ray on:

wikipedia
facebook
youtube
The Ray Code
Ray Andrade

Friday, May 14, 2021

Command pattern c++

The Command interface declares a method for executing a command. Command.h
class Command {
public:
    virtual ~Command() {
    }
    virtual void Execute() const = 0;
};
Some commands can implement simple operations on their own.
class SimpleCommand : public Command {
private:
    std::string pay_load_;

public:
    explicit SimpleCommand(std::string pay_load) : pay_load_(pay_load) {
    }
    void Execute() const override {
        std::cout << "SimpleCommand: does the request (" << this->pay_load_ << ")\n";
    }
};
The Receiver classes contain some important business logic. They know how to perform all kinds of operations, associated with carrying out a request. In fact, any class may serve as a Receiver.
class Receiver {
public:
    void DoWork(const std::string &a) {
        std::cout << "Receiver: Working on (" << a << ".)\n";
    }
    void DoSomeMoreWork(const std::string &b) {
        std::cout << "Receiver: Also working on (" << b << ".)\n";
    }
};
However, some commands can delegate more complex operations to other objects, called "receivers." Context data, required for launching the receiver's methods. Complex commands can accept one or several receiver objects along with any context data via the constructor. Commands can delegate to any methods of a receiver.
class ComplexCommand : public Command {
    /**
     * @var Receiver
     */
private:
    Receiver *receiver_;
    std::string a_;
    std::string b_;
public:
    ComplexCommand(Receiver *receiver, std::string a, std::string b) : receiver_(receiver), a_(a), b_(b) {
    }
    void Execute() const override {
        std::cout << "ComplexCommand: Complex stuff should be done by a receiver object.\n";
        this->receiver_->DoWork(this->a_);
        this->receiver_->DoSomeMoreWork(this->b_);
    }
};
The Invoker is associated with one or several commands. It sends a request to the command. Initialize commands. The Invoker does not depend on concrete command or receiver classes. The Invoker passes a request to a receiver indirectly, by executing a command.
class Invoker {
private:
    Command *on_start_;
    Command *on_finish_;
public:
    ~Invoker() {
        delete on_start_;
        delete on_finish_;
    }

    void SetOnStart(Command *command) {
        this->on_start_ = command;
    }
    void SetOnFinish(Command *command) {
        this->on_finish_ = command;
    }
    void DoSomethingImportant() {
        std::cout << "Invoker: Makes a request\n";
        if (this->on_start_) {
            this->on_start_->Execute();
        }
        std::cout << "Invoker: .does the action...\n";
        std::cout << "Invoker: Makes another request\n";
        if (this->on_finish_) {
            this->on_finish_->Execute();
        }
    }
};
we put it all together in the main method. The client code can parameterize an invoker with any commands.
int main() {
    Invoker *invoker = new Invoker;
    invoker->SetOnStart(new SimpleCommand("Say Hi!"));
    Receiver *receiver = new Receiver;
    invoker->SetOnFinish(new ComplexCommand(receiver, "Send email", "Save report"));
    invoker->DoSomethingImportant();

    delete invoker;
    delete receiver;
    return 0;
}
When we compile and run we should get:
Invoker: Makes a request
SimpleCommand: does the request (Say Hi!)
Invoker: .does the action...
Invoker: Makes another request
ComplexCommand: Complex stuff should be done by a receiver object.
Receiver: Working on (Send email.)
Receiver: Also working on (Save report.)
The Ray Code is AWESOME!!!
Find Ray on:

wikipedia
facebook
youtube
The Ray Code
Ray Andrade

Thursday, May 13, 2021

Chain-of-responsibility pattern php

We start by first creating an interface called Handler.
interface Handler
{
    public function setNext(Handler $handler): Handler;
    public function handle(string $request): ?string;
}
Next we will create an AbstractHandler which will be extened with the Handler interface.
class AbstractHandler implements Handler
{
    public function setNext(Handler $handler): Handler
    {
        $this->nextHandler = $handler;
        return $handler;
    }
    public function handle(string $request): ?string
    {
        if ($this->nextHandler) {
            return $this->nextHandler->handle($request);
        }
        return null;
    }
}
Let's create a menagerie of animals a cat, dog and a mouse. Each would like a treat so let code a senairo. Each will be extended with the AbstractHandler. For dog we have the DogHandler.
class DogHandler extends AbstractHandler
{
    public function handle(string $request): ?string
    {
        if ($request === "Bone") {
            return "Dog: I'll eat the " . $request . ".<br/>";
        } else {
            return parent::handle($request);
        }
    }
}
For the cat let's create a CatHandler.
class CatHandler extends AbstractHandler
{
    public function handle(string $request): ?string
    {
        if ($request === "Catnip") {
            return "Cat: I'll eat the " . $request . ".<br/>";
        } else {
            return parent::handle($request);
        }
    }
}
The last animal in our menagerie will be a mouse which is the MouseHandler.
class MouseHandler extends AbstractHandler
{
    public function handle(string $request): ?string
    {
        if ($request === "Cheese") {
            return "Mouse: I'll eat the " . $request . ".<br/>";
        } else {
            return parent::handle($request);
        }
    }
}


Let's put this altogether in the index.php
We first add the includes we need
include_once ('Handler.php');
include_once ('AbstractHandler.php');

include_once('CatHandler.php');
include_once('MouseHandler.php');
include_once ('DogHandler.php');
Let's add a client function
function clientCode(Handler $handler)
{
    foreach (["Catnip", "Bone", "Cup of coffee"] as $food) {
        echo "Client: Who wants a " . $food . "?<br/>";
        $result = $handler->handle($food);
        if ($result) {
            echo "  " . $result;
        } else {
            echo "  " . $food . " was left untouched.<br/>";
        }
    }
}
Now for the play/demo we put it altogether in the following statments.
$cat = new CatHandler;
$mouse = new MouseHandler;
$dog = new DogHandler;

$cat->setNext($mouse)->setNext($dog);

echo "Chain: Mouse > Cat > Dog<br/>";
clientCode($cat);
echo "<br/>";

echo "Subchain: Mouse > Dog<br/>";
clientCode($mouse);
Let's now look at this through a browser. You should have:
Chain: Mouse > Cat > Dog
Client: Who wants a Catnip?
Cat: I'll eat the Catnip.
Client: Who wants a Bone?
Dog: I'll eat the Bone.
Client: Who wants a Cup of coffee?
Cup of coffee was left untouched.

Subchain: Mouse > Dog
Client: Who wants a Catnip?
Catnip was left untouched.
Client: Who wants a Bone?
Dog: I'll eat the Bone.
Client: Who wants a Cup of coffee?
Cup of coffee was left untouched.
The Ray Code is AWESOME!!!
Find Ray on:

wikipedia
facebook
youtube
The Ray Code
Ray Andrade

Wednesday, May 12, 2021

Chain-of-responsibility pattern java

In this example I want to create a system that authorizes either a user or an administrator or basic user.
First we should create some packages that holds our code. The packages that I want to create are called **middleware** and **server**. These packages will be areas where we will add our java code files to. Now let's create some *class* files. The first class file I want to create will be an abstract class file we call: **Middleware**. Inside of the class file we add the following java code:
private Middleware next;

public Middleware linkWith(Middleware next) {
    this.next = next;
    return next;
}

public abstract boolean check(String email, String password);

protected boolean checkNext(String email, String password) {
    if (next == null) {
        return true;
    }
     return next.check(email, password);
}

The **linkwith** method takes the parameter **checkNext** and the parameter value gets returned as **next**. In the **checkNext** method I check to see if the parameters are of a certian type. There are only 2 users, **admin** and **user**. So for those at home, don't expect to put this demo into production. Now let's create a class named **ThrottlingMiddleware** and have it **extend**s **Middleware**. Override **check (String email, String password)** replace return false with. First we need some local varables:
private int requestPerMinute;
private int request;
private long currentTime;
and now we code our method:
public ThrottlingMiddleware(int requestPerMinute) {
    this.requestPerMinute = requestPerMinute;
    this.currentTime = System.currentTimeMillis();
 }
The next thing to add is to the override method **check** we repace the **return false** with:
if (System.currentTimeMillis() > currentTime + 60_000) {
    request = 0;
    currentTime = System.currentTimeMillis();
}

request++;

if (request > requestPerMinute) {
    System.out.println("Request limit exceeded!");
    Thread.currentThread().stop();
}
return checkNext(email, password);
create paclkage called server and add class **Server** to it do the following imports:
import java.util.HashMap;
import java.util.Map;
import TheRayCode.ChainOfResponsibility.middleware.Middleware;
add code:
private Map<String, String> users = new HashMap<>();

private Middleware middleware;
private Middleware next;

public Middleware linkWith(Middleware next) {
    this.next = next;
    return next;
}

public void setMiddleware(Middleware middleware) {
    this.middleware = middleware;
}

public boolean logIn(String email, String password) {
    if (middleware.check(email, password)) {
        System.out.println("Authorization have been successful!");
        return true;
    }
    return false;
}

public void register(String email, String password) {
    users.put(email, password);
}

public boolean hasEmail(String email) {
    return users.containsKey(email);
}

public boolean isValidPassword(String email, String password) {
    return users.get(email).equals(password);
}
create class **UserExistsMiddleware** have it **extends Middleware** override **check** (String email, String password) with:
if (!server.hasEmail(email)) {
    System.out.println("This email is not registered!");
    return false;
}
if (!server.isValidPassword(email, password)) {
    System.out.println("Wrong password!");
    return false;
}
return checkNext(email, password);
add:
private Server server;
and
public UserExistsMiddleware(Server server) {
        this.server = server;
 }

create class **RoleCheckMiddleware** have it **extends Middleware** override **check** (String email, String password) with:
if (email.equals("admin@example.com")) {
  System.out.println("Hello, admin!");
  return true;
}
System.out.println("Hello, user!");
return checkNext(email, password);
create paclage **server** add class **Server** go to **Demo** add imports:
import TheRayCode.ChainOfResponsibility.middleware.Middleware;
import TheRayCode.ChainOfResponsibility.middleware.RoleCheckMiddleware;
import TheRayCode.ChainOfResponsibility.middleware.ThrottlingMiddleware;
import TheRayCode.ChainOfResponsibility.middleware.UserExistsMiddleware;
import TheRayCode.ChainOfResponsibility.server.Server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

to the class **Demo**
public static void main(String[] args) { }
add:
throws IOException
add local method:
private static void init() { }
let now add some code to this method
server = new Server();
server.register("admin@example.com", "admin_pass");
server.register("user@example.com", "user_pass");
and..
Middleware middleware = new ThrottlingMiddleware(2);
middleware.linkWith(new UserExistsMiddleware(server)).linkWith(new RoleCheckMiddleware());
server.setMiddleware(middleware);
Let's close out this totrial by adding some code using to the **init** we just created, in the **main** method we add.
init();

boolean success;
do {
    System.out.print("Enter email: ");
    String email = reader.readLine();
    System.out.print("Input password: ");
    String password = reader.readLine();
    success = server.logIn(email, password);
} while (!success);
Let's run this an see what happens:
Enter email: admin@example.com
Input password: admin_pass
Hello, admin!
Authorization have been successful!
and let's run again:
Enter email: user@example.com
Input password: user_pass
Hello, user!
Authorization have been successful!

Find Ray on:

wikipedia
facebook
youtube
The Ray Code
Ray Andrade

Tuesday, May 11, 2021

Chain-of-responsibility pattern c#

The Handler interface declares a method for building the chain of handlers. It also declares a method for executing a request.
public interface Handler
{
    Handler SetNext(Handler handler);
    object Handle(object request);
}
The default chaining behavior can be implemented inside a base handler class. Returning a handler from here will let us link handlers in a convenient way like this: mouse.SetNext(cat).SetNext(dog); AbstractHandler.cs
abstract class AbstractHandler : Handler
{
    private Handler _nextHandler;
    public Handler SetNext(Handler handler)
    {
        this._nextHandler = handler;
        return handler;
    }
        
    public virtual object Handle(object request)
    {
        if (this._nextHandler != null)
        {
            return this._nextHandler.Handle(request);
        }
        else
        {
            return null;
        }
    }
}
All Concrete Handlers either handle a request or pass it to the next handler in the chain. First we create a MouseHandler.cs
class MouseHandler : AbstractHandler
{
    public override object Handle(object request)
    {
       if ((request as string) == "Cheese")
       {
           return $"Mouse: I'll eat the {request.ToString()}.\n";
       }
       else
       {
           return base.Handle(request);
       }
    }
}
Now we create a CatHandler.cs
class CatHandler : AbstractHandler
{
    public override object Handle(object request)
    {
        if (request.ToString() == "Catnip")
        {
            return $"Cat: I love {request.ToString()}.\n";
        }
        else
        {
            return base.Handle(request);
        }
    }
}
An fially we add a DogHandler.cs.
class DogHandler : AbstractHandler
{
    public override object Handle(object request)
    {
        if (request.ToString() == "Bone")
        {
            return $"Dog: Oh my!! I'll eat the {request.ToString()}.\n";
        }
        else
        {
            return base.Handle(request);
        }
    }
}
The client code is usually suited to work with a single handler. In most cases, it is not even aware that the handler is part of a chain.
class Client
{
    public static void ClientCode(AbstractHandler handler)
    {
        foreach (var food in new List<string> { "Bone", "Catnip", "Cheese" })
        {
            Console.WriteLine($"Client: Who wants a {food}?");
            var result = handler.Handle(food);
            if (result != null)
            {
                Console.Write($"   {result}");
            }
            else
            {
                Console.WriteLine($"   {food} was left untouched.");
            }
        }
    }
}
The other part of the client code constructs the actual chain. The client should be able to send a request to any handler, not just the first one in the chain. Program.cs
class Program
{
    static void Main(string[] args)
    {
        var mouse = new MouseHandler();
        var cat = new CatHandler();
        var dog = new DogHandler();

        mouse.SetNext(cat).SetNext(dog);

        Console.WriteLine("Chain: Dog > Cat > Mouse\n");
        Client.ClientCode(mouse);
        Console.WriteLine();

        Console.WriteLine("Subchain: Dog > Cat\n");
        Client.ClientCode(cat);
    }
}
Let's compile and run. We should get:
Chain: Dog > Cat > Mouse
Client: Who wants a Bone?
   Dog: Oh my!! I'll eat the Bone.
Client: Who wants a Catnip?
   Cat: I love Catnip.
Client: Who wants a Cheese?
   Mouse: I'll eat the Cheese.

Subchain: Dog > Cat
Client: Who wants a Bone?
   Dog: Oh my!! I'll eat the Bone.
Client: Who wants a Catnip?
   Cat: I love Catnip.
Client: Who wants a Cheese?
   Cheese was left untouched.
Or shall I say the cheese stands alone.
The Ray Code is AWESOME!!!
The Ray Code is AWESOME!!!
wikipedia

Find Ray on:

facebook
youtube
The Ray Code
Ray Andrade

The Strategy Design Pattern a Behavioral Pattern using C++

The Strategy Design Pattern is a behavioral design pattern that enables selecting an algorithm's implementation at runtime. Instead of i...