Tuesday, January 30, 2024

C++ Mediator Design Pattern using C++

The Mediator design pattern is used to centralize complex communications and control between related objects, making it easier to decouple them. Here's a simple example using a chat room (Mediator) where users (Colleagues) can send messages to each other:

1. 'Mediator.h`
This is an abstract class that declares the `sendMessage` method.


#include <string>

class User;

class Mediator {
public:
    virtual void sendMessage(const std::string& message, User* user) = 0;
};

2. `User.h`
This represents a colleague class. Each user knows about the mediator and can send messages.
#include "Mediator.h"
#include <iostream>

class User {
protected:
    Mediator* _mediator;
    std::string _name;

public:
    User(Mediator* mediator, const std::string& name) : _mediator(mediator), _name(name) {}
    virtual ~User() {}

    void sendMessage(const std::string& message) {
        _mediator->sendMessage(message, this);
    }

    virtual void receiveMessage(const std::string&smp; message) {
        std::cout << _name << " received: " << message << std::endl;
    }

    const std::string& getName() const { return _name; }
};

3. `ChatRoom.h`
This concrete mediator allows users to send messages to each other.
#include "Mediator.h"
#include "User.h"
#include <vector>

class ChatRoom : public Mediator {
private:
    std::vector<User*> _users;

public:
    void addUser(User* user) {
        _users.push_back(user);
    }

    void sendMessage(const std::string& message, User* user) override {
        for (User* u : _users) {
            // Don't send the message back to the sender
            if (u != user) {
                u->receiveMessage(user->getName() + ": " + message);
            }
        }
    }
};

4. `main.cpp`
This is a simple demo using the classes.
cpp
#include "ChatRoom.h"

int main() {
    ChatRoom chatRoom;

    User* alice = new User(&chatRoom, "Alice");
    User* bob = new User(&chatRoom, "Bob");

    chatRoom.addUser(alice);
    chatRoom.addUser(bob);

    alice->sendMessage("Hi Bob!");
    bob->sendMessage("Hello Alice!");

    delete alice;
    delete bob;

    return 0;
}
When you run this, you will get:
Bob received: Alice: Hi Bob!
Alice received: Bob: Hello Alice!

Explanation:

1. Mediator: Abstract class to define the contract for concrete mediators.
2. User: Represents the colleagues that will communicate using the Mediator.
3. ChatRoom: Concrete mediator that allows `User` instances to communicate with each other.
4. main.cpp: Demonstrates the usage of the pattern.

The idea is that a `User` doesn't communicate with other users directly. Instead, they use the `ChatRoom` (mediator) to pass messages. The mediator then decides how to propagate that message, allowing for easy modification of behavior without changing the `User` classes.

Saturday, January 20, 2024

The Iterator design pattern useing PHP

To demonstrate the Iterator design pattern in PHP, we'll create a simple example that iterates over a collection of books. The Iterator pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Project Structure
Book.php - Represents a single book.
BookList.php - Represents a collection of books.
BookListIterator.php - An iterator for the BookList.
index.php - Demonstrates the usage of the iterator.

Step-by-Step Creation and Explanation
1. Book.php This class represents a single book. It's a simple class with a constructor and a getter method for the book's title.
title = $title;
    }

    public function getTitle() {
        return $this->title;
    }
}

2. BookList.php This class represents a collection of Book objects. It stores books and provides methods to add or remove a book from the list.
books[] = $book;
    }

    public function removeBook(Book $book) {
        foreach ($this->books as $key => $b) {
            if ($b->getTitle() === $book->getTitle()) {
                unset($this->books[$key]);
            }
        }
        $this->books = array_values($this->books);
    }

    public function count() {
        return count($this->books);
    }

    public function getBook($index) {
        if (isset($this->books[$index])) {
            return $this->books[$index];
        }
        return null;
    }
}

3. BookListIterator.php This class implements the iterator for BookList. It allows traversing over the BookList collection.
bookList = $bookList;
    }

    public function hasNext() {
        return $this->currentBook < $this->bookList->count();
    }

    public function next() {
        return $this->bookList->getBook($this->currentBook++);
    }
}

4. index.php This file demonstrates the usage of the above classes. It creates a list of books, adds them to the BookList, and then iterates over them using BookListIterator.
addBook(new Book("1984"));
$bookList->addBook(new Book("To Kill a Mockingbird"));
$bookList->addBook(new Book("The Great Gatsby"));

// Iterate over book list
$iterator = new BookListIterator($bookList);
while ($iterator->hasNext()) {
    $book = $iterator->next();
    echo $book->getTitle() . "\n";
}
Running the Code When you run index.php, you should see the titles of the books printed one after the other:
1984
To Kill a Mockingbird
The Great Gatsby
This output demonstrates the Iterator pattern in action, allowing you to sequentially access elements of the BookList without exposing its internal structure.

Thursday, January 18, 2024

The Interpreter design pattern using Java

The Interpreter design pattern is used to provide a way to evaluate language grammar for particular languages. Here's a simple example using the pattern to interpret basic arithmetic expressions: code Expression.java - This is the abstract expression class that declares an interpret method.
public interface Expression {
    int interpret();
}
NumberExpression.java - This is a terminal expression that implements the Expression interface for numbers.
public class NumberExpression implements Expression {

    private int number;

    public NumberExpression(int number) {
        this.number = number;
    }

    @Override
    public int interpret() {
        return this.number;
    }
}
AddExpression.java - This is a non-terminal expression that implements the Expression interface for the addition operation.
public class AddExpression implements Expression {

    private Expression firstExpression;
    private Expression secondExpression;

    public AddExpression(Expression firstExpression, Expression secondExpression) {
        this.firstExpression = firstExpression;
        this.secondExpression = secondExpression;
    }

    @Override
    public int interpret() {
        return this.firstExpression.interpret() + this.secondExpression.interpret();
    }
}
SubtractExpression.java - This is a non-terminal expression for the subtraction operation.
public class SubtractExpression implements Expression {

    private Expression firstExpression;
    private Expression secondExpression;

    public SubtractExpression(Expression firstExpression, Expression secondExpression) {
        this.firstExpression = firstExpression;
        this.secondExpression = secondExpression;
    }

    @Override
    public int interpret() {
        return this.firstExpression.interpret() - this.secondExpression.interpret();
    }
}
Demo.java - This is the client class to demonstrate the Interpreter pattern.
public class Demo {

    // Typically, there would be a parser here to convert a string expression into the
    // Expression tree. For simplicity, we'll hand-code the tree.
    public static void main(String[] args) {
        Expression addExpression = new AddExpression(new NumberExpression(5), new NumberExpression(3));
        System.out.println("Result of 5 + 3: " + addExpression.interpret());

        Expression subtractExpression = new SubtractExpression(new NumberExpression(5), new NumberExpression(3));
        System.out.println("Result of 5 - 3: " + subtractExpression.interpret());
    }
}
Order of creating classes:
Expression.java - Define the interface for our expression tree.
NumberExpression.java - Define how numbers will be interpreted.
AddExpression.java and SubtractExpression.java - Define non-terminal expressions for addition and subtraction.
Demo.java - Use the above expressions to demonstrate the pattern.

Explanation:

Expression is an interface with the interpret method that all terminal and non-terminal expressions will implement.

NumberExpression is a terminal expression. It simply returns its number value when interpret is called.

AddExpression and SubtractExpression are non-terminal expressions. They contain two expressions and when interpret is called, they perform their respective operations on the results of the interpret calls of their contained expressions.

Demo constructs an expression tree and then evaluates it using the interpret method. In a real-world scenario, you'd probably have a parser that converts a string representation of an expression into this tree.

run code:
Result of 5 + 3: 8
Result of 5 - 3: 2

Tuesday, January 16, 2024

Chain Of Responsibility Design Pattern using C++

Alright, imagine for a moment that you have a series of people in a room. Each person is trying to avoid doing a specific task, so they keep passing it on to the next person saying, "Not my job!". That's essentially the Chain of Responsibility pattern! The idea is to decouple the sender from the receiver by allowing multiple objects to handle the request.

Let's look at a C++ example where different members of a household are trying to avoid doing the dishes:

DishWasher.h
#ifndef _DISHWASHER_H_
#define _DISHWASHER_H_

#include <iostream>
#include <memory>

class DishWasher {
public:
    virtual ~DishWasher() = default;
    void setNext(std::shared_ptr<DishWasher> nextWasher) { this->nextWasher = nextWasher; }
    virtual void washDishes(const std::string& dishType) = 0;

protected:
    std::shared_ptr<DishWasher> nextWasher;
};

#endif
Teenager.h
#ifndef _TEENAGER_H_
#define _TEENAGER_H_

#include "DishWasher.h"

class Teenager : public DishWasher {
public:
    void washDishes(const std::string& dishType) override {
        if (dishType == "Plate") {
            std::cout << "Teenager: Fine! I'll wash the plate.\n";
        } else {
            std::cout << "Teenager: Not my job! Passing it on...\n";
            if (nextWasher) nextWasher->washDishes(dishType);
        }
    }
};

#endif
Parent.h
#ifndef _PARENT_H_
#define _PARENT_H_

#include "DishWasher.h"

class Parent : public DishWasher {
public:
    void washDishes(const std::string& dishType) override {
        if (dishType == "Pot") {
            std::cout << "Parent: Alright, I'll wash the pot.\n";
        } else {
            std::cout << "Parent: Not my responsibility! Passing it on...\n";
            if (nextWasher) nextWasher->washDishes(dishType);
        }
    }
};

#endif
Robot.h
#ifndef _ROBOT_H_
#define _ROBOT_H_

#include "DishWasher.h"

class Robot : public DishWasher {
public:
    void washDishes(const std::string& dishType) override {
        std::cout << "Robot: Fine humans, I'll wash the " << dishType << ".\n";
    }
};

#endif

main.cpp
#include "Teenager.h"
#include "Parent.h"
#include "Robot.h"

int main() {
    auto teen = std::make_shared<Teenager>();
    auto parent = std::make_shared<Parent>();
    auto robot = std::make_shared<Robot>();

    teen->setNext(parent);
    parent->setNext(robot);

    std::cout << "Attempting to wash a Plate:\n";
    teen->washDishes("Plate");

    std::cout << "\nAttempting to wash a Glass:\n";
    teen->washDishes("Glass");

    return 0;
}

In this funny example, when you try to wash a plate, the teenager reluctantly agrees. But if it's anything else, they pass it on. The parent only washes pots, and if it's anything else, they pass it on. The robot, being the last in the chain (and the most responsible one), washes anything that reaches it! 😂

The Command design pattern useing C#

The Command design pattern is a behavioral pattern used in software design to encapsulate a request as an object, thereby allowing users to parameterize clients with queues, requests, and operations. It also allows for the support of undoable operations. In the context of C#, implementing this pattern typically involves creating a command interface, concrete command classes, a client, an invoker, and a receiver. Let's break down an example in C#, with each class in its own `.cs` file for clarity:
1. `ICommand.cs` (Command Interface)
This interface declares an execution method that all concrete command classes will implement.
public interface ICommand
{
    void Execute();
}
2. `Light.cs` (Receiver) The receiver class performs the actual work. Here, we use a simple example of a `Light` that can be turned on and off.
public class Light
{
    public void TurnOn() => Console.WriteLine("Light is on");
    public void TurnOff() => Console.WriteLine("Light is off");
}
3. `LightOnCommand.cs` and `LightOffCommand.cs` (Concrete Commands) These classes implement the `ICommand` interface, invoking actions on the receiver.
public class LightOnCommand : ICommand
{
    private Light _light;

    public LightOnCommand(Light light)
    {
        _light = light;
    }

    public void Execute()
    {
        _light.TurnOn();
    }
}

public class LightOffCommand : ICommand
{
    private Light _light;

    public LightOffCommand(Light light)
    {
        _light = light;
    }

    public void Execute()
    {
        _light.TurnOff();
    }
}
4. `RemoteControl.cs` (Invoker) This class asks the command to carry out the request.
public class RemoteControl
{
    private ICommand _command;

    public void SetCommand(ICommand command)
    {
        _command = command;
    }

    public void PressButton()
    {
        _command.Execute();
    }
}

5. `Program.cs` (Client) This is the entry point where we tie everything together and demonstrate the pattern.
class Program
{
    static void Main(string[] args)
    {
        var light = new Light();
        var lightOn = new LightOnCommand(light);
        var lightOff = new LightOffCommand(light);

        var remote = new RemoteControl();

        remote.SetCommand(lightOn);
        remote.PressButton(); // Output: Light is on

        remote.SetCommand(lightOff);
        remote.PressButton(); // Output: Light is off
    }
}

Order of Creation and Execution
1. Define the `ICommand` Interface: It's the foundation of the command pattern.

2. Create the `Receiver` Class (`Light.cs`): It's the class that knows how to perform the operations.

3. Implement Concrete Commands (`LightOnCommand.cs` and `LightOffCommand.cs`): These classes encapsulate the action and its parameters.

4. Create the `Invoker` Class (`RemoteControl.cs`): This will use command objects to perform actions.

5. Assemble in the `Program.cs` file: This is where you create instances and demonstrate the usage of the command pattern. Expected Terminal Output When you run `Program.cs`, you should expect to see the following output in the terminal:
Light is on
Light is off
This simple example demonstrates the essence of the Command design pattern in a C# context. You can expand upon this by introducing more complex commands and receivers.

Saturday, January 06, 2024

The Decorator pattern using C++

Creating a C++ example using the Decorator Design Pattern involves several steps. This design pattern is used to add new functionalities to objects dynamically without altering their structure. Here's how you can structure your C++ project using this pattern: Project Structure Component.h - Abstract base class declaring the common interface. ConcreteComponent.h - Class implementing the Component interface. Decorator.h - Abstract class inheriting from Component, used as a base for concrete decorators. ConcreteDecoratorA.h, ConcreteDecoratorB.h, etc. - Concrete classes extending Decorator with additional functionalities. main.cpp - The main program to demonstrate the usage. Explanation of Each File Component.h
// Component.h
#ifndef COMPONENT_H
#define COMPONENT_H

// Abstract base class representing the primary interface
class Component {
public:
    virtual ~Component() {}
    virtual void operation() = 0;
};
#endif
ConcreteComponent.h
// ConcreteComponent.h

#ifndef CONCRETECOMPONENT_H
#define CONCRETECOMPONENT_H

#include "Component.h"
#include <iostream>

// Concrete implementation of Component
class ConcreteComponent : public Component {
public:
    void operation() override {
        std::cout << "Basic functionality.\n";
    }
};

#endif
Decorator.h
// Decorator.h
#ifndef DECORATOR_H
#define DECORATOR_H

#include "Component.h"

// Base decorator class
class Decorator : public Component {
protected:
    Component* component;

public:
    Decorator(Component* c) : component(c) {}
    void operation() override {
        if (component)
            component->operation();
    }
};

#endif
ConcreteDecoratorA.h
// ConcreteDecoratorA.h
#ifndef CONCRETEDECORATORA_H
#define CONCRETEDECORATORA_H

#include "Decorator.h"
#include <iostream>

// A concrete decorator adding extra features
class ConcreteDecoratorA : public Decorator {
public:
    ConcreteDecoratorA(Component* c) : Decorator(c) {}

    void operation() override {
        Decorator::operation();
        addedBehavior();
    }

private:
    void addedBehavior() {
        std::cout << "Added behavior A.\n";
    }
};
#endif main.cpp
// main.cpp
#include "ConcreteComponent.h"
#include "ConcreteDecoratorA.h"

int main() {
    Component* simple = new ConcreteComponent();
    Component* decorated = new ConcreteDecoratorA(simple);

    std::cout << "Running basic component:\n";
    simple->operation();

    std::cout << "\nRunning decorated component:\n";
    decorated->operation();

    delete simple;
    delete decorated;
    return 0;
}
Order of Creation Component.h:
Define the base interface.
ConcreteComponent.h: 
Implement the basic functionality.
Decorator.h 
Create the base decorator.
ConcreteDecoratorA.h: 
Add specific functionalities.
main.cpp: Demonstrate the pattern.
Expected Output in Terminal

When you run main.cpp, 
you should see the following output:
Running basic component:
Basic functionality.

Running decorated component:
Basic functionality.
Added behavior A.
This project demonstrates the Decorator Pattern in C++ where ConcreteDecoratorA adds additional behavior to ConcreteComponent dynamically.

Composite Design Pattern using PHP

Teaching the Composite design pattern in PHP is a great way to introduce students to both advanced object-oriented programming concepts and design patterns. The Composite pattern is particularly useful for treating individual objects and compositions of objects uniformly. In the Composite pattern, you typically have a component interface, leaf objects, and composite objects. The component interface defines default behavior for all objects, leaf objects perform actual operations, and composite objects store child components (which can be leaf or composite objects). Let's create a simple example: a file system with directories and files. Directories can contain files or other directories. Step 1: Define the Component Interface FileComponent.php

Step 2: Create Leaf Objects
FileLeaf.php
name = $name;
        $this->size = $size;
    }

    public function getSize() {
        return $this->size;
    }

    public function getName() {
        return $this->name;
    }
}
Step 3: Create Composite Objects DirectoryComposite.php
name = $name;
        $this->children = [];
    }

    public function add(FileComponent $component) {
        $this->children[] = $component;
    }

    public function getSize() {
        $totalSize = 0;
        foreach ($this->children as $child) {
            $totalSize += $child->getSize();
        }
        return $totalSize;
    }

    public function getName() {
        return $this->name;
    }
}
Step 4: Demonstrate the Composite Pattern index.php
add($file1);
$directory->add($file2);

// Create a subdirectory and add it to the directory
$subdirectory = new DirectoryComposite("Subdirectory");
$subdirectory->add(new FileLeaf("SubFile1.txt", 110));
$directory->add($subdirectory);

// Display the size of the directory
echo "Total Size of '" . $directory->getName() . "': " . $directory->getSize() . " bytes";
Order of Creation
FileComponent.php:
Define the component interface. FileLeaf.php:
Implement the leaf objects. DirectoryComposite.php:
Implement the composite objects. index.php:
Demonstrate the usage of the Composite pattern. Expected Output When you run index.php,
you should see the total size of the directory, which includes the sizes of all files in it and its subdirectories.
The output will be:
Total Size of 'Directory': 630 bytes

Thursday, January 04, 2024

Java Bridge Design Pattern


The Bridge design pattern is a structural pattern used to decouple an abstraction from its implementation so that the two can vary independently. This pattern involves an interface which acts as a bridge between the abstraction and its implementation classes. It's particularly useful for scenarios where an abstraction can have multiple implementations.

To demonstrate the Bridge pattern in Java, let's consider a simple example of a TV remote control (the abstraction) and different types of TVs (the implementations). We'll create a hierarchy where the remote control can work with any TV type without being tightly coupled to a specific TV implementation.
Here's how you can structure the classes:

1. RemoteControl.java: An abstract class representing the abstraction. It contains a reference to a TV interface.
2. TV.java: An interface representing the implementer. This will be implemented by different types of TVs.
3. SonyTV.java and SamsungTV.java: Concrete implementations of the TV interface.
4. Main.java: Contains the main method to demonstrate the use of the Bridge pattern.

Step-by-Step Implementation
1. TV.java (Interface) This interface declares methods that will be implemented by concrete TV classes.
public interface TV {
    void on();
    void off();
    void tuneChannel(int channel);
}

2. SonyTV.java (Concrete Implementation)
Implements the `TV` interface, representing a specific type of TV.
public class SonyTV implements TV {
    public void on() {
        System.out.println("Sony TV: ON");
    }

    public void off() {
        System.out.println("Sony TV: OFF");
    }

    public void tuneChannel(int channel) {
        System.out.println("Sony TV: Tuned to channel " + channel);
    }
}

3. SamsungTV.java (Concrete Implementation)
Another implementation of the `TV` interface.
public class SamsungTV implements TV {
    public void on() {
        System.out.println("Samsung TV: ON");
    }

    public void off() {
        System.out.println("Samsung TV: OFF");
    }

    public void tuneChannel(int channel) {
        System.out.println("Samsung TV: Tuned to channel " + channel);
    }
}

4. RemoteControl.java (Abstraction)
This abstract class represents a generic remote control. It holds a reference to a `TV` object and delegates the TV-related operations to it.
public abstract class RemoteControl {
    protected TV tv;

    public RemoteControl(TV tv) {
        this.tv = tv;
    }

    public abstract void turnOn();
    public abstract void turnOff();
    public abstract void setChannel(int channel);
}

5. Main.java (Demonstration)
This class demonstrates the use of the Bridge pattern.
public class Main {
    public static void main(String[] args) {
        TV sonyTv = new SonyTV();
        RemoteControl sonyRemote = new ConcreteRemote(sonyTv);

        sonyRemote.turnOn();
        sonyRemote.setChannel(9);
        sonyRemote.turnOff();

        TV samsungTv = new SamsungTV();
        RemoteControl samsungRemote = new ConcreteRemote(samsungTv);

        samsungRemote.turnOn();
        samsungRemote.setChannel(5);
        samsungRemote.turnOff();
    }
}

class ConcreteRemote extends RemoteControl {
    public ConcreteRemote(TV tv) {
        super(tv);
    }

    public void turnOn() {
        tv.on();
    }

    public void turnOff() {
        tv.off();
    }

    public void setChannel(int channel) {
        tv.tuneChannel(channel);
    }
}

Order of Creation
1. Create the TV interface. 2. Implement the `TV` interface in SonyTV and SamsungTV.
3. Create the RemoteControl abstract class.
4. Implement a concrete remote control in ConcreteRemote.
5. Use the `Main` class to demonstrate the pattern.

Output When Running the Code
When you run the Main.java, you should see output demonstrating the interaction between the remote controls and their respective TVs:
Sony TV: ON
Sony TV: Tuned to channel 9
Sony TV: OFF
Samsung TV: ON
Samsung TV: Tuned to channel 5
Samsung TV: OFF
This output shows how the Bridge pattern allows different types of TVs to be controlled by a generic remote control without tightly coupling the remote control class to specific TV classes.

Tuesday, January 02, 2024

Adapter design pattern in C#

Creating an example of the Adapter design pattern in C#

involves several components. The Adapter pattern is a structural design pattern that allows objects with incompatible interfaces to collaborate. It involves at least three roles: the Client, the Target, and the Adapter. Sometimes, there's also an Adaptee - the class that is being adapted to the Target interface.
Structure:
1. Target Interface: This is the interface that the Client expects to work with.
2. Adapter Class: This adapts the interface of the Adaptee to the Target interface.
3. Adaptee Class: This is the class that needs adapting to be used by the Client.
4. Client Class: This uses the Target interface.
Example:

1. ITarget.cs - Target Interface
public interface ITarget
{
    string GetRequest();
}

Explanation: ITarget is the interface expected by the Client. It defines the domain-specific interface that Client uses.

2. Adaptee.cs - Adaptee Class
public class Adaptee
{
    public string GetSpecificRequest()
    {
        return "Specific request.";
    }
}

Explanation: Adaptee is the class that has a different interface and needs to be adapted.

3. Adapter.cs - Adapter Class
public class Adapter : ITarget
{
    private readonly Adaptee _adaptee;

    public Adapter(Adaptee adaptee)
    {
        _adaptee = adaptee;
    }

    public string GetRequest()
    {
        return $"This is '{_adaptee.GetSpecificRequest()}'";
    }
}

Explanation: Adapter makes Adaptee's interface compatible with the ITarget interface.

4. Client.cs - Client Class
public class Client
{
    public void Main()
    {
        Adaptee adaptee = new Adaptee();
        ITarget target = new Adapter(adaptee);

        Console.WriteLine("Adaptee interface is incompatible with the client.");
        Console.WriteLine("But with adapter client can call it's method.");

        Console.WriteLine(target.GetRequest());
    }
}

Explanation: Client is a class that depends on the ITarget interface. It's unaware of Adaptee and Adapter.

5. Program.cs - Main Program
class Program
{
    static void Main(string[] args)
    {
        new Client().Main();
    }
}

*Explanation*: This is the entry point of the program, creating and running the client's main method. Order of Creation: 1. ITarget.cs
2. Adaptee.cs
3. Adapter.cs
4. Client.cs
5. Program.cs
Expected Output When Running the Code:
Adaptee interface is incompatible with the client.
But with adapter client can call it's method.
This is Specific request.

This example demonstrates how the Adapter pattern can be used to integrate classes with incompatible interfaces. The Client can use the Adaptee via the Adapter without changing its code.

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