Tuesday, June 15, 2021

Observer pattern PHP

The Observer is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they’re observing.

The object that has some interesting state is often called subject, but since it’s also going to notify other objects about the changes to its state, we’ll call it publisher. All other objects that want to track changes to the publisher’s state are called subscribers.

The UserRepository represents a Subject. Various objects are interested in tracking its internal state, whether it's adding a new user or removing one.

PHP has a couple of built-in interfaces related to the Observer pattern. The Subject owns some important state and notifies observers when the state changes. In real life, the list of subscribers can be stored more comprehensively (categorized by event type, etc. The Subject owns some important state and notifies observers when the state changes. For the sake of simplicity, the Subject's state, essential to all subscribers, is stored in this variable. The subscription management methods the also Trigger an update in each subscriber.

Usually, the subscription logic is only a fraction of what a Subject can really do. Subjects commonly hold some important business logic, that triggers a notification method whenever something important is about to happen (or after it).
class Subject implements \SplSubject
{
    public $state;
    private $observers;
    public function __construct()
    {
        $this->observers = new \SplObjectStorage;
    }

    public function attach(SplObserver $observer): void
    {
        echo "Subject: Attached an observer.<br/>";
        $this->observers->attach($observer);
    }
    public function detach(SplObserver $observer): void
    {
        $this->observers->detach($observer);
        echo "Subject: Detached an observer.<br/>";
    }
    public function notify(): void
    {
        echo "Subject: Notifying observers...<br/>";
        foreach ($this->observers as $observer) {
            $observer->update($this);
        }
    }
    public function someBusinessLogic(): void
    {
        echo "\nSubject: I'm doing something important.<br/>";
        $this->state = rand(0, 10);

        echo "Subject: My state has just changed to: {$this->state}<br/>";
        $this->notify();
    }
}
Concrete Observers react to the updates issued by the Subject they had been attached to.
class ConcreteObserverA implements SplObserver
{
    public function update(\SplSubject $subject): void
    {
        if ($subject->state < 3) {
            echo "ConcreteObserverA: Reacted to the event.<br/>";
        }
    }
}
Let's also create another concrete observer we call ConcreteObserverB.
class ConcreteObserverB implements SplObserver
{
    public function update(\SplSubject $subject): void
    {
        if ($subject->state == 0 || $subject->state >= 2) {
            echo "ConcreteObserverB: Reacted to the event.<br/>";
        }
    }
}
Now let put this all together in an index.php file and we have.
include_once ('Subject.php');
include_once ('ConcreteObserverA.php');
include_once ('ConcreteObserverB.php');
$subject = new Subject;

$o1 = new ConcreteObserverA;
$subject->attach($o1);

$o2 = new ConcreteObserverB;
$subject->attach($o2);

$subject->someBusinessLogic();
$subject->someBusinessLogic();

$subject->detach($o2);

$subject->someBusinessLogic();
Now whe view our projext through a browser we have
Subject: Attached an observer.
Subject: Attached an observer.
Subject: I'm doing something important.
Subject: My state has just changed to: 4
Subject: Notifying observers...
ConcreteObserverB: Reacted to the event.
Subject: I'm doing something important.
Subject: My state has just changed to: 3
Subject: Notifying observers...
ConcreteObserverB: Reacted to the event.
Subject: Detached an observer.
Subject: I'm doing something important.
Subject: My state has just changed to: 1
Subject: Notifying observers...
ConcreteObserverA: Reacted to the event.
The Ray Code is AWESOME!!!
Find Ray on:

wikipedia
facebook
youtube
The Ray Code
Ray Andrade

Monday, June 14, 2021

Observer pattern java

In this example, the Observer pattern establishes indirect collaboration between objects of a text editor. Each time the Editor object changes, it notifies its subscribers. EmailNotificationListener and LogOpenListener react to these notifications by executing their primary behaviors.
Subscriber classes aren’t coupled to the editor class and can be reused in other apps if needed. The Editor class depends only on the abstract subscriber interface. This allows adding new subscriber types without changing the editor’s code.
We create a package called listeners and in that package we create an interface called interface.
import java.io.File;

public interface EventListener {
    void update(String eventType, File file);
}
To the package called listeners we add the class file call EmailNotificationListener. This class implements EventListener.
import java.io.File;

public class EmailNotificationListener implements EventListener {
    private String email;

    public EmailNotificationListener(String email) {
        this.email = email;
    }

    @Override
    public void update(String eventType, File file) {
        System.out.println("Email to " + email + ": Someone has performed " + eventType + " operation with the following file: " + file.getName());
    }
}
We also add another class file called LogOpenListener. LogOpenListener also implements the EventListener interface.
import java.io.File;

public class LogOpenListener implements EventListener {
    private File log;

    public LogOpenListener(String fileName) {
        this.log = new File(fileName);
    }

    @Override
    public void update(String eventType, File file) {
        System.out.println("Save to log " + log + ": Someone has performed " + eventType + " operation with the following file: " + file.getName());
    }
}
We creater a package called editor and in this package we place a class called Editor in there.
import java.io.File;

public class Editor {
    public EventManager events;
    private File file;

    public Editor() {
        this.events = new EventManager("open", "save");
    }

    public void openFile(String filePath) {
        this.file = new File(filePath);
        events.notify("open", file);
    }

    public void saveFile() throws Exception {
        if (this.file != null) {
            events.notify("save", file);
        } else {
            throw new Exception("Please open a file first.");
        }
    }
}
We create another package called publisher. In this package we place a class file called the EventManager.
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EventManager {
    Map<tring, List<EventListener>> listeners = new HashMap<>();

    public EventManager(String... operations) {
        for (String operation : operations) {
            this.listeners.put(operation, new ArrayList<>());
        }
    }

    public void subscribe(String eventType, EventListener listener) {
        List<EventListener> users = listeners.get(eventType);
        users.add(listener);
    }

    public void unsubscribe(String eventType, EventListener listener) {
        List<EventListener> users = listeners.get(eventType);
        users.remove(listener);
    }

    public void notify(String eventType, File file) {
        List<EventListener> users = listeners.get(eventType);
        for (EventListener listener : users) {
            listener.update(eventType, file);
        }
    }
}
Let's put this altogether in a class we call Demo.
import TheRayCode.observer.example.editor.Editor;
import TheRayCode.observer.example.listeners.EmailNotificationListener;
import TheRayCode.observer.example.listeners.LogOpenListener;

public class Demo {
    public static void main(String[] args) {
        Editor editor = new Editor();
        editor.events.subscribe("open", new LogOpenListener("/path/to/log/file.txt"));
        editor.events.subscribe("save", new EmailNotificationListener("admin@example.com"));

        try {
            editor.openFile("test.txt");
            editor.saveFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
When we compile and run, we get.
Save to log /path/to/log/file.txt: Someone has performed open operation with the following file: test.txt
Email to admin@example.com: Someone has performed save operation with the following file: test.txt
The Ray Code is AWESOME!!!
Find Ray on:

wikipedia
facebook
youtube
The Ray Code
Ray Andrade

Saturday, June 12, 2021

Observer pattern c#

Receive update from subject, we create an interface we call IObserver.
public interface IObserver
{
    // Receive update from subject
    void Update(ISubject subject);
}
We create another interface we call the ISubject. The method of this interface are Attach, Detach and Notify. Attach attaches the observer to the subject. Detach detaches them. Notify will notify of the process.
public interface ISubject
{
    void Attach(IObserver observer);
    void Detach(IObserver observer);
    void Notify();
}
Let's create a couple of Observers we call Observer1 and Observer2. Concrete Observers react to the updates issued by the Subject they had been attached to.
class Observer1 : IObserver
{
    public void Update(ISubject subject)
    {            
        if ((subject as Subject).State < 3)
        {
           Console.WriteLine("Concrete Observer1: Reacted to the event.");
        }
    }
}
Let's also create the second Observer Observer2.
class Observer2 : IObserver
{
    public void Update(ISubject subject)
    {
        if ((subject as Subject).State == 0 || (subject as Subject).State >= 2)
        {
            Console.WriteLine("Observer2: Reacted to the event.");
        }
    }
}
Now let's put this all together in the Main method found in the Program class.
static void Main(string[] args)
{
    var subject = new Subject();
    var observer1 = new Observer1();
    subject.Attach(observer1);
    var observer2 = new Observer2();
    subject.Attach(observer2);

    subject.SomeBusinessLogic();
    subject.SomeBusinessLogic();
    subject.Detach(observer2);
    subject.SomeBusinessLogic();
    }
}
When we compiled this and run it, we should get
Subject: Attached an observer.
Subject: Attached an observer.

Subject: I'm doing something important.
Subject: My state has just changed to: 1
Subject: Notifying observers...
Concrete Observer1: Reacted to the event.

Subject: I'm doing something important.
Subject: My state has just changed to: 4
Subject: Notifying observers...
Observer2: Reacted to the event.
Subject: Detached an observer.

Subject: I'm doing something important.
Subject: My state has just changed to: 6
Subject: Notifying observers...
The Ray Code is AWESOME!!!
Find Ray on:

wikipedia
facebook
youtube
The Ray Code
Ray Andrade

Thursday, June 03, 2021

Observer pattern c++

The intent of the Observer pattern is to let you define a subscription mechanism to notify multiple objects about any events that happen to the object they're observing. Notis that there's a lot of different terms with similar meaning associated with this pattern. Just remember that the Subject is also called the Publisher and the Observer is often called the Subscriber and vice versa. Also notice the verbs "observe", "listen" or "track" usually mean the same thing.
class IObserver {
public:
    virtual ~IObserver(){};
    virtual void Update(const std::string &message_from_subject) = 0;
};
class ISubject {
public:
    virtual ~ISubject(){};
    virtual void Attach(IObserver *observer) = 0;
    virtual void Detach(IObserver *observer) = 0;
    virtual void Notify() = 0;
};
The Subject owns some important state and notifies observers when the state changes. The subscription management methods are Attach, Detach, Notify, CreateMessage and HowManyObserver. Usually, the subscription logic is only a fraction of what a Subject can really do. Subjects commonly hold some important business logic, that triggers a notification method whenever something important is about to happen (or after it).
class Subject : public ISubject {
public:
    virtual ~Subject() {
        std::cout << "Goodbye, I was the Subject.\n";
    }
    void Attach(IObserver *observer) override {
        list_observer_.push_back(observer);
    }
    void Detach(IObserver *observer) override {
        list_observer_.remove(observer);
    }
    void Notify() override {
        std::list<IObserver *>::iterator iterator = list_observer_.begin();
        HowManyObserver();
        while (iterator != list_observer_.end()) {
            (*iterator)->Update(message_);
            ++iterator;
        }
    }
    void CreateMessage(std::string message = "Empty") {
        this->message_ = message;
        Notify();
    }
    void HowManyObserver() {
        std::cout << "There are " << list_observer_.size() << " observers in the list.\n";
    }
    void SomeBusinessLogic() {
        this->message_ = "change message message";
        Notify();
        std::cout << "I'm about to do some thing important\n";
    }
private:
    std::list<IObserver *> list_observer_;
    std::string message_;
};
We create an **Observer** class that will be extended with the **IObserver** interface.
class Observer : public IObserver {
public:
    Observer(Subject &subject) : subject_(subject) {
        this->subject_.Attach(this);
        std::cout << "Hi, I'm the Observer \"" << ++Observer::static_number_ << "\".\n";
        this->number_ = Observer::static_number_;
    }
    virtual ~Observer() {
        std::cout << "Goodbye, I was the Observer \"" << this->number_ << "\".\n";
    }
    void Update(const std::string &message_from_subject) override {
        message_from_subject_ = message_from_subject;
        PrintInfo();
    }
    void RemoveMeFromTheList() {
        subject_.Detach(this);
        std::cout << "Observer \"" << number_ << "\" removed from the list.\n";
    }
    void PrintInfo() {
        std::cout << "Observer \"" << this->number_ << "\": a new message is available --> " << this->message_from_subject_ << "\n";
    }
private:
    std::string message_from_subject_;
    Subject &subject_;
    static int static_number_;
    int number_;
};
Now let's build a demo of our project. In the main.cpp where we placed the main method. But we first add some ClientCode.
int Observer::static_number_ = 0;

void ClientCode() {
    Subject *subject = new Subject;
    Observer *observer1 = new Observer(*subject);
    Observer *observer2 = new Observer(*subject);
    Observer *observer3 = new Observer(*subject);
    Observer *observer4;
    Observer *observer5;

    subject->CreateMessage("Hello World! :D");
    observer3->RemoveMeFromTheList();

    subject->CreateMessage("The weather is hot today! :p");
    observer4 = new Observer(*subject);

    observer2->RemoveMeFromTheList();
    observer5 = new Observer(*subject);

    subject->CreateMessage("My new car is great! ;)");
    observer5->RemoveMeFromTheList();

    observer4->RemoveMeFromTheList();
    observer1->RemoveMeFromTheList();

    delete observer5;
    delete observer4;
    delete observer3;
    delete observer2;
    delete observer1;
    delete subject;
}
and the in the main method itself.
int main() {
    ClientCode();
    return 0;
}
When we compile and run we should get:
Hi, I'm the Observer "1".
Hi, I'm the Observer "2".
Hi, I'm the Observer "3".
There are 3 observers in the list.
Observer "1": a new message is available --> Hello World! :D
Observer "2": a new message is available --> Hello World! :D
Observer "3": a new message is available --> Hello World! :D
Observer "3" removed from the list.
There are 2 observers in the list.
Observer "1": a new message is available --> The weather is hot today! :p
Observer "2": a new message is available --> The weather is hot today! :p
Hi, I'm the Observer "4".
Observer "2" removed from the list.
Hi, I'm the Observer "5".
There are 3 observers in the list.
Observer "1": a new message is available --> My new car is great! ;)
Observer "4": a new message is available --> My new car is great! ;)
Observer "5": a new message is available --> My new car is great! ;)
Observer "5" removed from the list.
Observer "4" removed from the list.
Observer "1" removed from the list.
Goodbye, I was the Observer "5".
Goodbye, I was the Observer "4".
Goodbye, I was the Observer "3".
Goodbye, I was the Observer "2".
Goodbye, I was the Observer "1".
Goodbye, I was the Subject.
The Ray Code is AWESOME!!!
Find Ray on:

wikipedia
facebook
youtube
The Ray Code
Ray Andrade

Wednesday, June 02, 2021

Memento pattern php

The Memento interface provides a way to retrieve the memento's metadata, suchas creation date or name. However, it doesn't expose the Originator's state.
interface Memento
{
    public function getName(): string;

    public function getDate(): string;
}
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. The **save() method Saves the current state inside a memento. The restore(Memento $memento) Restores the Originator's state from a memento object.
class Originator
{
    private $state;
    public function __construct(string $state)
    {
        $this->state = $state;
        echo "Originator: My initial state is: {$this->state}<br/>";
    }
    public function doSomething(): void
    {
        echo "Originator: I'm doing something important.<br/>";
        $this->state = $this->generateRandomString(30);
        echo "Originator: and my state has changed to: {$this->state}<br/>";
    }

    private function generateRandomString(int $length = 10): string
    {
        return substr(
            str_shuffle(
                str_repeat(
                    $x = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
                    ceil($length / strlen($x))
                )
            ),
            1,
            $length
        );
    }

    public function save(): Memento
    {
        return new ConcreteMemento($this->state);
    }
    public function restore(Memento $memento): void
    {
        $this->state = $memento->getState();
        echo "Originator: My state has changed to: {$this->state}<br/>";
    }
}
The Concrete Memento contains the infrastructure for storing the Originator's state.
The Originator uses this method when restoring its state.
class ConcreteMemento implements Memento
{
    private $state;

    private $date;

    public function __construct(string $state)
    {
        $this->state = $state;
        $this->date = date('Y-m-d H:i:s');
    }
    public function getState(): string
    {
        return $this->state;
    }

    /**
     * The rest of the methods are used by the Caretaker to display metadata.
     */
    public function getName(): string
    {
        return $this->date . " / (" . substr($this->state, 0, 9) . "...)";
    }

    public function getDate(): string
    {
        return $this->date;
    }
}
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 $mementos = [];
    private $originator;
    public function __construct(Originator $originator)
    {
        $this->originator = $originator;
    }
    public function backup(): void
    {
        echo "\nCaretaker: Saving Originator's state...<br/>";
        $this->mementos[] = $this->originator->save();
    }
    public function undo(): void
    {
        if (!count($this->mementos)) {
            return;
        }
        $memento = array_pop($this->mementos);
        echo "Caretaker: Restoring state to: " . $memento->getName() . "<br/>";
        try {
            $this->originator->restore($memento);
        } catch (\Exception $e) {
            $this->undo();
        }
    }
    public function showHistory(): void
    {
        echo "Caretaker: Here's the list of mementos:<br/>";
        foreach ($this->mementos as $memento) {
            echo $memento->getName() . "<br/>";
        }
    }
}
Let's go to the index.php files and to the the to we add our includes/
include_once ('Originator.php');
include_once ('Memento.php');
include_once ('ConcreteMemento.php');
include_once ('Caretaker.php');
Client code.
$originator = new Originator("Super-duper-super-puper-super.");
$caretaker = new Caretaker($originator);

$caretaker->backup();
$originator->doSomething();

$caretaker->backup();
$originator->doSomething();

$caretaker->backup();
$originator->doSomething();

echo "\n";
$caretaker->showHistory();

echo "\nClient: Now, let's rollback!<br/><br/>";
$caretaker->undo();

echo "\nClient: Once more!<br/><br/>";
$caretaker->undo();
Now let's view this thru a browser. We should have:
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

Tuesday, June 01, 2021

Memento pattern java

Using the memento design pattern we can restore an object to its previous state and undo or rollback operations. We start with by creating a LedTV class will represent a LED TV. We add variables for the size, price and USB suport. The variables for the size, price and USB suport can be pass in at initaition.
public class LedTV {
    private String  size;
    private String  price;
    private boolean usbSupport;

    public LedTV( String size, String price, boolean usbSupport ) {
        super();
        this.size = size;
        this.price = price;
        this.usbSupport = usbSupport;
    }

    public String getSize(){
        return size;
    }
    public void setSize( String size ){
        this.size = size;
    }
    public String getPrice(){
        return price;
    }
    public void setPrice( String price ){
        this.price = price;
    }
    public boolean isUsbSupport(){
        return usbSupport;
    }
    public void setUsbSupport( boolean usbSupport ){
        this.usbSupport = usbSupport;
    }
    @Override
    public String toString(){
        return "LedTV [size=" + size + ", price=" + price + ", usbSupport=" + usbSupport + "]";
    }
}
We create a class for our Memento object. The Memento class is used to store the state of the object.
public class Memento {
    private LedTV ledTV;

    public Memento( LedTV ledTV ) {
        super();
        this.ledTV = ledTV;
    }
    public LedTV getLedTV(){
        return ledTV;
    }
    public void setLedTV( LedTV ledTV ) {
        this.ledTV = ledTV;
    }
    @Override
    public String toString() {
        return "Memento [ledTV=" + ledTV + "]";
    }
}
The Caretaker is the 'storeroom' and it will maintain the memento object.
import java.util.ArrayList;
import java.util.List;

public class Caretaker {

    private List<Memento> ledTvList = new ArrayList<Memento>();

    public void addMemento( Memento m ) {
        ledTvList.add(m);
        System.out.println("LED TV's snapshots Maintained by CareTaker :" + ledTvList);
    }

    public Memento getMemento( int index ) {
        return ledTvList.get(index);
    }
}
The Originator is a hub that contains the ledTV. The Originator can invoke the createMemento to create a new Memento object The setMemento can be use to initlize the Memento.
public class Originator {
    LedTV ledTV;
    public LedTV getLedTV(){
        return ledTV;
    }
    public void setLedTV( LedTV ledTV ){
        this.ledTV = ledTV;
    }
    public Memento createMemento(){
        return new Memento(ledTV);
    }
    public void setMemento( Memento memento ){
        ledTV = memento.getLedTV();
    }
    @Override
    public String toString() {
        return "Originator [ledTV=" + ledTV + "]";
    }
}
We put this altogether in the main method we find it in the MementoClient. This method is used to demo to Memento design pattern.
public class MementoClient {
    public static void main( String[] args ) {
        Originator originator = new Originator();
        originator.setLedTV(new LedTV("42 inch", "60000Rs", false));
        Caretaker caretaker = new Caretaker();
        caretaker.addMemento(originator.createMemento());
        originator.setLedTV(new LedTV("46 inch", "80000Rs", true));
        caretaker.addMemento(originator.createMemento());
        originator.setLedTV(new LedTV("50 inch", "100000Rs", true));
        System.out.println("\nOrignator current state : " + originator);
        System.out.println("\nOriginator restoring to 42 inch LED TV...");
        originator.setMemento(caretaker.getMemento(0));
        System.out.println("\nOrignator current state : " + originator);

    }
}
Let's compile and run we should get...
LED TV's snapshots Maintained by CareTaker :[Memento [ledTV=LedTV [size=42 inch, price=60000Rs, usbSupport=false]]]
LED TV's snapshots Maintained by CareTaker :[Memento [ledTV=LedTV [size=42 inch, price=60000Rs, usbSupport=false]], Memento [ledTV=LedTV [size=46 inch, price=80000Rs, usbSupport=true]]]

Orignator current state : Originator [ledTV=LedTV [size=50 inch, price=100000Rs, usbSupport=true]]

Originator restoring to 42 inch LED TV...

Orignator current state : Originator [ledTV=LedTV [size=42 inch, price=60000Rs, usbSupport=false]]
The Ray Code is AWESOME!!!
Find Ray on:

wikipedia
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...