Showing posts with label Behavioral. Show all posts
Showing posts with label Behavioral. Show all posts

Friday, March 13, 2026

Chain of Responsibility Design Pattern in PHP

Chain of Responsibility Design Pattern in PHP

🔗 What Is the Chain of Responsibility Pattern?

The Chain of Responsibility is a behavioral design pattern that lets you pass a request through a chain of handlers, where each handler decides either to process the request or pass it to the next handler in line.

Think of it like a helpdesk ticket system — your request moves up the support chain until someone has the authority or ability to resolve it.


🤔 Why Would I Use It in PHP?

  • When multiple classes could handle a request and you don’t want the sender to know which one will do it.
  • When you want to decouple the sender and receiver, making the system easier to maintain.
  • When you need a flexible structure for handling requests such as logging, validation, or middleware.

✅ Benefits of Using It in PHP

  • Enables clean separation of concerns by letting each handler focus on a specific task.
  • Makes code extensible, allowing handlers to be added, removed, or reordered easily.
  • Reduces tight coupling between components sending and processing requests.

UML / ORM

🌟 Chain of Responsibility — Participants (for PHP Students)

Handler

  • Defines the interface for handling requests.
  • Stores a reference to the next handler.
  • Forwards requests if it cannot handle them.

ConcreteHandler

  • Handles requests it is responsible for.
  • Decides whether to process or forward.
  • Passes unhandled requests to the successor.

Client

  • Sends requests to the first handler.
  • Does not know which handler processes the request.
  • Relies on the chain to handle requests.

PHP 8.2 Implementation

Handler.php

<?php
interface Handler
{
    public function setNext(Handler $handler): Handler;

    public function handle(string $request): ?string;
}

AbstractHandler.php

<?php
require_once 'Handler.php';

abstract class AbstractHandler implements Handler
{
    protected ?Handler $nextHandler = null;

    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;
    }
}

ConcreteHandlerA.php

<?php
require_once 'AbstractHandler.php';

class ConcreteHandlerA extends AbstractHandler
{
    public function handle(string $request): ?string
    {
        if ($request === 'A') {
            return "Handler A: I handled the request.";
        }

        return parent::handle($request);
    }
}

ConcreteHandlerB.php

<?php
require_once 'AbstractHandler.php';

class ConcreteHandlerB extends AbstractHandler
{
    public function handle(string $request): ?string
    {
        if ($request === 'B') {
            return "Handler B: I handled the request.";
        }

        return parent::handle($request);
    }
}

ConcreteHandlerC.php

<?php
require_once 'AbstractHandler.php';

class ConcreteHandlerC extends AbstractHandler
{
    public function handle(string $request): ?string
    {
        if ($request === 'C') {
            return "Handler C: I handled the request.";
        }

        return parent::handle($request);
    }
}

index.php

setNext($b)->setNext($c);

$requests = ['A','B','C','D'];

foreach ($requests as $request) {

    echo "Client: Who can handle '$request'?\n";

    $result = $a->handle($request);

    if ($result) {
        echo $result . "\n";
    } else {
        echo "No handler could handle the request.\n";
    }

    echo "----------------------------------------\n";
}

Expected Output

Client: Who can handle 'A'?
Handler A: I handled the request.
----------------------------------------
Client: Who can handle 'B'?
Handler B: I handled the request.
----------------------------------------
Client: Who can handle 'C'?
Handler C: I handled the request.
----------------------------------------
Client: Who can handle 'D'?
No handler could handle the request.

🧠 S.W.O.T. Analysis — Chain of Responsibility in PHP

Strengths

  1. Promotes flexibility by allowing dynamic addition or removal of handlers.
  2. Makes request processing modular and maintainable.
  3. Reduces large conditional logic by delegating responsibility.

Weaknesses

  1. Debugging may be harder when requests travel through the entire chain.
  2. Performance may degrade if the chain grows too long.
  3. Overuse may introduce unnecessary complexity.

Opportunities

  1. Helps build middleware-style request pipelines.
  2. Encourages modular responsibility delegation.
  3. Provides foundation for PSR-15 middleware frameworks.

Threats

  1. Misordered handlers may cause incorrect processing.
  2. Tightly coupled handlers defeat the pattern’s purpose.
  3. Poor exit conditions may result in unhandled requests.

Chain of Responsibility Design Pattern in Java

Chain of Responsibility Design Pattern in Java

The Chain of Responsibility Design Pattern enables decoupling between senders and receivers by allowing multiple objects to handle a request. The core idea is that a request is passed along a chain of potential handler objects. Each handler decides either to process the request or pass it to the next handler in the chain.

The sender of the request is unaware of which object in the chain will ultimately handle the request, ensuring that the sender and receiver operate independently.


Why Java Programmers Should Study the Chain of Responsibility Pattern

  1. Request Handling – Simplifies request processing by allowing multiple objects to handle a request dynamically.
  2. Decoupling Logic – Separates sender and receiver, improving maintainability and flexibility in evolving Java applications.
  3. Dynamic Responsibility – Enables defining or modifying the chain of responsibility at runtime.
  4. Error Handling – Useful for building robust error-handling chains where multiple modules can validate or log issues sequentially.
  5. Command Validation – Allows commands or user inputs to be validated through a series of validation handlers.
  6. Scalable Workflows – New handlers can be added or removed without modifying existing logic.
  7. Middleware Simulation – Simulates middleware behavior such as authentication, logging, and rate limiting in server-side Java applications.

Participants (for Java Students)

Handler

  • Defines the interface for handling requests.
  • Stores a reference to the next handler.
  • Forwards requests if it cannot handle them.

ConcreteHandler

  • Handles requests it is responsible for.
  • Decides whether to process or forward.
  • Passes unhandled requests to the successor.

Client

  • Sends requests to the first handler.
  • Does not know which handler processes the request.
  • Relies on the chain to handle requests.

Java Example — Sandwich Maker Chain

Imagine a chain of sandwich makers. Each maker specializes in adding one specific ingredient. If they don’t have that ingredient, they pass the sandwich down the line to the next expert.

SandwichMaker.java


public abstract class SandwichMaker {
    protected SandwichMaker nextMaker;

    public void setNextMaker(SandwichMaker nextMaker) {
        this.nextMaker = nextMaker;
    }

    public abstract void addIngredient(String ingredient);
}

BreadMaker.java


public class BreadMaker extends SandwichMaker {
    @Override
    public void addIngredient(String ingredient) {
        if (ingredient.equals("bread")) {
            System.out.println("BreadMaker: Toasting the bread. Nice and crispy!");
        } else {
            System.out.println("BreadMaker: I only deal with bread. Passing on...");
            if (nextMaker != null) nextMaker.addIngredient(ingredient);
        }
    }
}

LettuceAdder.java


public class LettuceAdder extends SandwichMaker {
    @Override
    public void addIngredient(String ingredient) {
        if (ingredient.equals("lettuce")) {
            System.out.println("LettuceAdder: Adding fresh green lettuce. Crunchy!");
        } else {
            System.out.println("LettuceAdder: Lettuce only, buddy. Next please...");
            if (nextMaker != null) nextMaker.addIngredient(ingredient);
        }
    }
}

CheeseSpreader.java


public class CheeseSpreader extends SandwichMaker {
    @Override
    public void addIngredient(String ingredient) {
        if (ingredient.equals("cheese")) {
            System.out.println("CheeseSpreader: Adding a thick slice of cheese. Yummy!");
        } else {
            System.out.println("CheeseSpreader: Cheese, please! Handing off...");
            if (nextMaker != null) nextMaker.addIngredient(ingredient);
        }
    }
}

Main.java


public class Main {
    public static void main(String[] args) {

        SandwichMaker breadMaker = new BreadMaker();
        SandwichMaker lettuceAdder = new LettuceAdder();
        SandwichMaker cheeseSpreader = new CheeseSpreader();

        breadMaker.setNextMaker(lettuceAdder);
        lettuceAdder.setNextMaker(cheeseSpreader);

        System.out.println("Making a sandwich with bread:\n");
        breadMaker.addIngredient("bread");

        System.out.println("\nMaking a sandwich with lettuce:\n");
        breadMaker.addIngredient("lettuce");

        System.out.println("\nMaking a sandwich with pickles:\n");
        breadMaker.addIngredient("pickles");
    }
}

Example Output


Making a sandwich with bread:

BreadMaker: Toasting the bread. Nice and crispy!

Making a sandwich with lettuce:

BreadMaker: I only deal with bread. Passing on...
LettuceAdder: Adding fresh green lettuce. Crunchy!

Making a sandwich with pickles:

BreadMaker: I only deal with bread. Passing on...
LettuceAdder: Lettuce only, buddy. Next please...
CheeseSpreader: Cheese, please! Handing off...

In this amusing sandwich shop, the BreadMaker only toasts bread, the LettuceAdder specializes in crunchy greens, and the CheeseSpreader focuses on that delicious cheese slice. If you ask for pickles though, the sandwich just travels through the chain with everyone passing it along, puzzled!


S.W.O.T. Analysis — Chain of Responsibility Pattern

Strengths

  1. Dynamic Workflow – Supports dynamic and flexible request-handling pipelines.
  2. Extensibility – Easily extended by adding new handlers.
  3. Decoupling – Clean separation between senders and receivers.

Weaknesses

  1. Execution Overhead – Long chains may reduce performance.
  2. Complex Debugging – Tracing requests through many handlers can be difficult.
  3. Order Dependency – Incorrect ordering of handlers may cause unexpected behavior.

Opportunities

  1. Middleware Pipelines – Useful for building middleware in Java frameworks.
  2. Event Handling – Effective for GUI and event-based systems.
  3. Authorization Chains – Ideal for multi-step authorization systems.

Threats

  1. Scalability Risks – Extremely long chains may impact scalability.
  2. Mismanagement – Poor chain management may introduce unexpected failures.
  3. Alternative Patterns – In some cases, patterns like State or Observer may be more appropriate.

Chain of Responsibility Design Pattern in JavaScript

Chain of Responsibility Design Pattern in JavaScript

🔗 What Is the Chain of Responsibility Design Pattern?

The Chain of Responsibility pattern is a behavioral pattern that lets you pass a request along a chain of handlers, where each handler decides whether to process it or pass it on.

Think of it like a customer service line: if the first person can’t help, they pass you to the next, until someone handles your issue.


🤔 Why Would I Use It?

  • When you want to avoid coupling the sender of a request to its receiver.
  • When you have multiple objects that might handle a request, but you don’t know which one ahead of time.
  • When you want to build flexible, dynamic chains for handling commands or events.

✅ Benefits of the Chain of Responsibility Pattern

  • Makes it easy to add or remove handlers without breaking other parts of the system.
  • Encourages loose coupling between senders and receivers of requests.
  • Supports flexible, reusable workflows where the order of handlers can change dynamically.

🧩 Summary

The Chain of Responsibility is about passing the buck until someone takes it:

“I’ll forward your call until the right person can answer it.”

It’s great for building flexible pipelines and event-handling systems.


UML / ORM Breakdown

1. Client

Starts the chain by making a request. Doesn’t worry about who will handle it — just gives it to the first link in the chain.

Example: “I need this done — whoever can handle it, please do.”

2. Handler

Sets the rule that every handler can either deal with the request or pass it along. Keeps a reference to the next handler in the chain.

Think of it as: “If I can’t do it, I’ll ask the next person.”

3. ConcreteHandler

Knows how to handle specific types of requests. If it recognizes the request, it takes care of it. If not, it forwards the request to the next handler.

In other words: “Not mine — passing it on.”


JavaScript Example

Below is a JavaScript example of the Chain of Responsibility pattern as described in the Design Patterns GoF book (pages 223–232), with the UML on page 223.

Participants in the GoF structure:

  • Handler — defines the interface to handle the request and set successor
  • ConcreteHandler — concrete implementation that either handles or forwards the request
  • Client — sends requests into the chain

This example includes:

  • Explanation of each class outside the code block
  • Fully commented code
  • Each class in its own .js module
  • A working index.js demo
  • GitHub-style README structure

🧩 Class-by-Class Explanation

🧩 Handler.js

Purpose

This is the abstract class (in JavaScript, a base class) that declares the handleRequest() method and holds the next handler in the chain. It defines the interface for chaining.

// Handler.js

// Handler is the base class for handling requests
class Handler {
    constructor() {
        this.successor = null; // next handler in the chain
    }

    // sets the next handler in the chain
    setSuccessor(successor) {
        this.successor = successor;
    }

    // defines the handling interface to override
    handleRequest(request) {
        throw new Error("handleRequest() must be implemented by subclasses.");
    }
}

module.exports = Handler;

🧩 ConcreteHandler1.js

Purpose

This concrete handler processes requests it understands; otherwise it forwards the request to its successor.

// ConcreteHandler1.js

const Handler = require('./Handler');

// ConcreteHandler1: handles requests in its range or forwards
class ConcreteHandler1 extends Handler {
    handleRequest(request) {
        // check if request is in range
        if (request >= 0 && request < 10) {
            console.log(`ConcreteHandler1 handled request ${request}`);
        } else if (this.successor) {
            console.log(`ConcreteHandler1 forwards ${request} to successor`);
            this.successor.handleRequest(request);
        }
    }
}

module.exports = ConcreteHandler1;

🧩 ConcreteHandler2.js

Purpose

This is another concrete handler in the chain. It handles a different range of requests or forwards them.

// ConcreteHandler2.js

const Handler = require('./Handler');

// ConcreteHandler2: handles requests in its range or forwards
class ConcreteHandler2 extends Handler {
    handleRequest(request) {
        // check if request is in range
        if (request >= 10 && request < 20) {
            console.log(`ConcreteHandler2 handled request ${request}`);
        } else if (this.successor) {
            console.log(`ConcreteHandler2 forwards ${request} to successor`);
            this.successor.handleRequest(request);
        }
    }
}

module.exports = ConcreteHandler2;

🧩 ConcreteHandler3.js

Purpose

A third handler in the chain, responsible for handling requests in its own range.

// ConcreteHandler3.js

const Handler = require('./Handler');

// ConcreteHandler3: handles requests in its range or ends the chain
class ConcreteHandler3 extends Handler {
    handleRequest(request) {
        // check if request is in range
        if (request >= 20 && request < 30) {
            console.log(`ConcreteHandler3 handled request ${request}`);
        } else {
            console.log(`ConcreteHandler3: no handler for ${request}`);
        }
    }
}

module.exports = ConcreteHandler3;

👤 Client.js

Purpose

The Client configures the chain of handlers and initiates the requests.

// Client.js

// Client builds the chain of handlers and sends requests
class Client {
    static run() {
        const ConcreteHandler1 = require('./ConcreteHandler1');
        const ConcreteHandler2 = require('./ConcreteHandler2');
        const ConcreteHandler3 = require('./ConcreteHandler3');

        const h1 = new ConcreteHandler1();
        const h2 = new ConcreteHandler2();
        const h3 = new ConcreteHandler3();

        // chain the handlers
        h1.setSuccessor(h2);
        h2.setSuccessor(h3);

        // issue requests
        const requests = [2, 5, 14, 22, 30];

        requests.forEach(request => {
            console.log(`Client: sending request ${request}`);
            h1.handleRequest(request);
        });
    }
}

module.exports = Client;

🚀 index.js

Purpose

This file starts the demonstration of the Chain of Responsibility pattern.

// index.js

const Client = require('./Client');

// start the Chain of Responsibility demo
Client.run();

✅ Expected Output

Client: sending request 2
ConcreteHandler1 handled request 2
Client: sending request 5
ConcreteHandler1 handled request 5
Client: sending request 14
ConcreteHandler1 forwards 14 to successor
ConcreteHandler2 handled request 14
Client: sending request 22
ConcreteHandler1 forwards 22 to successor
ConcreteHandler2 forwards 22 to successor
ConcreteHandler3 handled request 22
Client: sending request 30
ConcreteHandler1 forwards 30 to successor
ConcreteHandler2 forwards 30 to successor
ConcreteHandler3: no handler for 30

📚 References

  • Design Patterns: Elements of Reusable Object-Oriented Software (Gamma et al)
  • Chain of Responsibility Pattern, pages 223–232
  • UML page 223
  • Participants:
    • Handler
    • ConcreteHandler
    • Client

🧠 Teaching Notes

  • Explain how the chain is dynamic — the order or number of handlers can change at runtime.
  • Show how each handler either processes or forwards the request.
  • Discuss what happens when there is no handler for a request and the chain ends.

🧠 S.W.O.T. Analysis — Chain of Responsibility Pattern

✅ Strengths

  1. Simplifies client code by removing knowledge of who handles what request.
  2. Makes it easy to change the chain without affecting the client.
  3. Supports flexible and reusable request-handling pipelines.

❌ Weaknesses

  1. Can be hard to debug since requests may pass through many handlers.
  2. May result in requests not being handled if no handler takes responsibility.
  3. Adds complexity if the chain becomes too long or poorly organized.

🌱 Opportunities

  1. Helps juniors learn decoupled and modular request-processing techniques.
  2. Encourages designing systems that can grow or change handler order easily.
  3. Builds understanding for event systems, middleware, and interceptors.

⚠️ Threats

  1. Overuse may lead to tangled chains with unclear responsibilities.
  2. Improperly designed chains might skip critical processing steps.
  3. Performance may suffer if too many handlers are involved.

Chain of Responsibility Design Pattern in C#

Chain of Responsibility Design Pattern in C#

The Chain of Responsibility Design Pattern provides a mechanism to decouple senders from receivers by allowing more than one object to handle a request. In this pattern, a request is passed along a chain of potential handler objects until an object handles it or the chain's end is reached.

The key idea is that the sender broadcasts a request without knowing which object in the chain will serve the request, ensuring that the sender and receiver remain loosely coupled.


Why C# Programmers Should Study It

  1. Decoupling – Separates the sender of a request from the receiver, improving modular design.
  2. Flexible Request Handling – Handlers can be inserted, removed, or reordered easily.
  3. Maintainability – Each handler can be updated independently.
  4. Scalability – New handlers can be added without affecting existing code.
  5. Common in Middleware – Widely used in ASP.NET Core pipelines and other .NET middleware.
  6. Interception and Enhancements – Useful for logging, validation, and processing pipelines.
  7. Single Responsibility Principle – Each handler performs one task.
  8. Deepening OOP Mastery – Strengthens understanding of object-oriented design.
  9. Real-world Applicability – Useful for UI event processing and request pipelines.

Participants (for C# Students)

Handler

  • Declares the method for handling requests.
  • Stores a reference to the next Handler.
  • Forwards requests when unable to handle them.

ConcreteHandler

  • Handles requests within its responsibility range.
  • Decides whether to process or pass forward.
  • Sends unhandled requests to the successor.

Client

  • Sends request to the first handler.
  • Does not know which handler will process it.
  • Relies on the chain to manage the request.

C# Implementation

Handler Interface


public interface Handler
{
    Handler SetNext(Handler handler);
    object Handle(object request);
}

The default chaining behavior can be implemented in a base handler class. Returning the handler allows convenient chaining such as: 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;
        }
    }
}

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);
       }
    }
}

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);
        }
    }
}

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);
        }
    }
}

Client Code

The client usually interacts with a single handler and is unaware that a chain exists.


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.");
            }
        }
    }
}

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);
    }
}

Expected Output


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.


S.W.O.T. Analysis

Strengths

  • Encapsulates request processing into independent handlers.
  • Promotes separation of concerns.
  • Allows scalable request pipelines.
  • Maintains consistency in processing behavior.

Weaknesses

  • Introduces additional classes and interfaces.
  • Can increase complexity in small applications.
  • Extending handler types may require refactoring.

Opportunities

  • Works well with modern C# features like dependency injection.
  • Ideal for middleware pipelines in ASP.NET Core.
  • Highly applicable in enterprise software systems.

Threats

  • Risk of overengineering when unnecessary.
  • Potential performance overhead from multiple handlers.
  • Misuse by inexperienced developers can complicate architecture.

Tuesday, February 17, 2026

C++ Chain Of Responsibility Design Pattern with S.W.O.T. Analysis

Chain Of Responsibility Design Pattern

The Chain of Responsibility Design Pattern is a behavioral pattern that allows a request to pass through a chain of handlers until one of them handles it.

Instead of having a single object responsible for processing a request, multiple objects are given a chance to handle it. The request moves along the chain until it reaches an object capable of processing it.

This design pattern promotes loose coupling between the sender and receiver. The sender does not need to know which object will handle the request — only that the request will be handled somewhere in the chain.

By decoupling request senders from receivers, we create flexible, maintainable, and efficient design.


🧩 ORM / UML Structure

The UML structure of Chain of Responsibility contains three primary participants:

  • Handler (Interface / Abstract Class)
  • ConcreteHandler
  • Client

The key relationship is:

Client → Handler → ConcreteHandler → ConcreteHandler → ...

Each handler contains:

  • A reference to the next handler
  • A method to handle the request
  • Logic to either process or forward the request

The power of this pattern lies in the dynamic linking of handlers at runtime.


🌟 Chain of Responsibility — Participants (for C++ Students)

Handler

  • Defines the interface for handling requests.
  • Stores a reference to the next Handler.
  • Forwards requests if it cannot handle them.

ConcreteHandler

  • Handles requests it is responsible for.
  • Decides whether to process or forward.
  • Passes unhandled requests to successor.

Client

  • Sends requests to the first Handler.
  • Does not know which Handler processes it.
  • Relies on the chain for handling.

💻 C++ Code Example

Below is the example formatted cleanly for blog presentation.

Handler Interface

#ifndef HANDLER_H
#define HANDLER_H

#include <string>

class Handler {
protected:
    Handler* next;

public:
    Handler() : next(nullptr) {}

    virtual ~Handler() {}

    void setNext(Handler* handler) {
        next = handler;
    }

    virtual void handleRequest(const std::string& request) = 0;
};

#endif

ConcreteHandlerA

#ifndef CONCRETEHANDLERA_H
#define CONCRETEHANDLERA_H

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

class ConcreteHandlerA : public Handler {
public:
    void handleRequest(const std::string& request) override {
        if (request == "A") {
            std::cout << "ConcreteHandlerA handled request A\n";
        } else if (next) {
            next->handleRequest(request);
        }
    }
};

#endif

ConcreteHandlerB

#ifndef CONCRETEHANDLERB_H
#define CONCRETEHANDLERB_H

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

class ConcreteHandlerB : public Handler {
public:
    void handleRequest(const std::string& request) override {
        if (request == "B") {
            std::cout << "ConcreteHandlerB handled request B\n";
        } else if (next) {
            next->handleRequest(request);
        }
    }
};

#endif

main.cpp (Client)

#include "ConcreteHandlerA.h"
#include "ConcreteHandlerB.h"

int main() {
    ConcreteHandlerA handlerA;
    ConcreteHandlerB handlerB;

    handlerA.setNext(&handlerB);

    handlerA.handleRequest("A");
    handlerA.handleRequest("B");
    handlerA.handleRequest("C");

    return 0;
}

🧠 S.W.O.T. Analysis

✅ Strengths

  • Promotes loose coupling between sender and receiver.
  • Flexible and dynamic chain construction.
  • Respects Open/Closed Principle.

⚠️ Weaknesses

  • Can be harder to debug.
  • No guarantee a request will be handled.
  • Chain configuration must be done carefully.

🚀 Opportunities

  • Ideal for middleware systems.
  • Excellent for event processing pipelines.
  • Common in logging, GUI event handling, and request processing systems.

⚡ Threats

  • Long chains may reduce performance.
  • Improper chain setup can cause silent failures.
  • Overuse may complicate simple workflows.

Thursday, February 06, 2025

Creational Patterns in Java

Creational patterns in Java focus on simplifying and standardizing object creation while ensuring flexibility and minimizing dependencies.

1. Singleton

Ensures a class has only one instance, implemented using private constructors and synchronized methods for thread safety.

2. Factory Method

Defines a method for object creation, allowing subclasses to decide which class to instantiate dynamically.

3. Abstract Factory

Provides an interface for creating families of related objects without specifying their concrete implementations.

4. Builder

Separates the construction of complex objects from their representation, using fluent methods for flexibility and clarity.

5. Prototype

Creates new objects by cloning existing ones, leveraging Cloneable and overriding the clone() method for efficient duplication.

Structural Patterns in Java

Structural patterns emphasize organizing classes and objects for better composition, maintainability, and scalability in Java.

1. Adapter

Converts one interface into another expected by clients, using inheritance or delegation to bridge incompatibility.

2. Bridge

Decouples abstraction from implementation by combining interfaces and concrete implementations, enabling independent extension.

3. Composite

Groups objects into tree structures to represent part-whole hierarchies, leveraging recursion and polymorphism in Java.

4. Decorator

Dynamically adds behavior to objects without modifying their code, often using wrapping and interfaces.

5. Facade

Provides a unified interface to a complex subsystem, simplifying interaction by encapsulating multiple components into one.

6. Flyweight

Shares common state among multiple objects to reduce memory usage, using object pooling or caching mechanisms.

7. Proxy

Acts as a surrogate to control access to another object, often used for lazy initialization or access control.

Behavioral Patterns in Java

Behavioral patterns in Java manage communication and workflows between objects, enhancing flexibility and dynamic interactions.

1. Chain of Responsibility

Passes a request through a chain of handlers, each deciding whether to handle or forward it.

2. Command

Encapsulates requests as objects, allowing parameterization, queuing, and undo/redo functionality in Java applications.

3. Interpreter

Defines a grammar and interprets expressions, suitable for scripting engines, configuration parsers, or DSLs.

4. Iterator

Provides a standard way to traverse collections using Java’s Iterator or enhanced for-loops.

5. Mediator

Centralizes communication between objects, reducing dependencies with event-based systems or a mediator class.

6. Memento

Captures and restores an object’s state without exposing its details, commonly used for undo operations.

7. Observer

Implements a one-to-many relationship where dependents are notified of changes, often using Java’s Observer and Observable.

8. State

Allows an object to change its behavior dynamically based on its internal state, modeled using state classes.

9. Strategy

Encapsulates interchangeable algorithms into separate classes, promoting flexibility and reuse for tasks like sorting or validation.

10. Template Method

Defines the skeleton of an algorithm in a base class, deferring specific steps to subclasses.

11. Visitor

Encapsulates operations performed on elements of an object structure, enabling new functionality without modifying them.

C# Patterns Design Patterns study in C#

Creational Patterns in C#

Creational patterns in C# focus on efficient object creation while reducing coupling and promoting flexibility in design.

1. Singleton

Ensures a class has a single instance, using private constructors and static properties for controlled access.

2. Factory Method

Defines an interface for object creation, letting subclasses specify the type of objects to instantiate.

3. Abstract Factory

Provides an interface for creating families of related objects without specifying their concrete implementations.

4. Builder

Separates complex object construction from representation, enabling flexible configurations through method chaining in C#.

5. Prototype

Creates new objects by cloning existing ones, utilizing ICloneable and deep-copy techniques for duplicating complex objects.

Structural Patterns in C#

Structural patterns emphasize efficient class and object composition, ensuring modular, extensible, and scalable designs in C#.

1. Adapter

Converts one interface to another using inheritance or composition, allowing seamless integration of incompatible components.

2. Bridge

Decouples abstraction from implementation, enabling independent evolution of both through interfaces and composition in C#.

3. Composite

Organizes objects into tree structures to represent part-whole hierarchies, leveraging recursive relationships for complex systems.

4. Decorator

Adds responsibilities dynamically to objects without altering their structure, implemented with composition and interfaces.

5. Facade

Provides a simplified interface to complex subsystems, encapsulating their functionality into a single, cohesive API.

6. Flyweight

Minimizes memory usage by sharing common state among similar objects, often implemented with static caching in C#.

7. Proxy

Acts as a placeholder or surrogate, controlling access to another object using lazy loading or remote proxies.

Behavioral Patterns in C#

Behavioral patterns in C# manage object communication and workflows, promoting dynamic, loosely-coupled systems.

1. Chain of Responsibility

Passes requests through a chain of handlers, allowing each to decide whether to process or forward the request.

2. Command

Encapsulates requests as objects, enabling flexible execution, queuing, and undo/redo operations in C#.

3. Interpreter

Defines and evaluates a grammar for a language, suitable for scripting engines and domain-specific languages.

4. Iterator

Provides a standard way to traverse collections, leveraging IEnumerable and IEnumerator for seamless iteration.

5. Mediator

Centralizes communication between objects, reducing dependencies by using events, delegates, or a mediator class.

6. Memento

Captures and restores an object’s internal state without exposing implementation details, useful for undo functionality.

7. Observer

Establishes a one-to-many relationship where changes in one object notify dependents, using events or delegates.

8. State

Changes an object’s behavior based on its state, modeled using polymorphism or a state pattern implementation.

9. Strategy

Encapsulates algorithms within classes, allowing dynamic substitution of strategies for tasks like validation or sorting.

10. Template Method

Defines an algorithm’s skeleton in a base class, allowing subclasses to override specific steps while retaining structure.

11. Visitor

Encapsulates operations to be performed on object structures, enabling new functionality without altering the objects.

Tuesday, February 04, 2025

CPP Study

Study the Design Patterms using C++

Creational Patterns

Creational patterns in C++ focus on flexible object creation while minimizing coupling between classes and their implementations.

1. Singleton

Ensures a class has only one instance, using private constructors and static members for global access.

2. Factory Method

Defines an interface for object creation, delegating type determination to subclasses using inheritance and polymorphism.

3. Abstract Factory

Creates families of related objects without specifying concrete classes, leveraging abstract classes and templates in C++.

4. Builder

Separates complex object construction from representation, enabling fluent APIs for creating diverse configurations.

5. Prototype

Generates new objects by cloning existing ones using copy constructors and deep-copy mechanisms.

Structural Patterns

Structural patterns emphasize class and object composition, facilitating modular, scalable, and extensible C++ systems.

1. Adapter

Converts one interface into another using multiple inheritance or operator overloading to integrate legacy code seamlessly.

2. Bridge

Decouples abstraction from implementation using pointers and virtual functions for independent variation.

3. Composite

Represents part-whole hierarchies with recursive structures and polymorphism, ideal for file systems or graphical elements.

4. Decorator

Dynamically adds behavior to objects without altering their structure, leveraging composition and operator overloading.

5. Facade

Provides a unified interface to encapsulate complex subsystems into a single, simplified class.

6. Flyweight

Minimizes memory usage by sharing data between similar objects through object pooling and explicit memory control.

7. Proxy

Acts as a surrogate for another object, enabling lazy initialization, access control, or remote procedure calls.

Behavioral Patterns

Behavioral patterns facilitate object interactions and workflows, promoting dynamic communication and responsibility management.

1. Chain of Responsibility

Passes requests along a chain of handlers, implemented via function pointers or object references.

2. Command

Encapsulates requests as objects, enabling parameterization, queuing, and undo/redo functionality using callable objects.

3. Interpreter

Defines and evaluates grammars or expressions, suitable for scripting engines or mathematical computations.

4. Iterator

Provides a uniform way to traverse collections without exposing their internal structure, exemplified by STL iterators.

5. Mediator

Centralizes communication between objects, reducing dependencies, often implemented in GUI frameworks with observer patterns.

6. Memento

Captures and restores an object's state using serialization libraries or copy constructors.

7. Observer

Establishes one-to-many relationships, notifying dependents of changes using event-based systems or signals/slots.

8. State

Changes an object's behavior dynamically based on its internal state using polymorphism or function pointers.

9. Strategy

Encapsulates interchangeable algorithms, implemented efficiently with templates and function objects for diverse use cases.

10. Template Method

Defines an algorithm’s skeleton in base classes, deferring specific steps to subclasses via inheritance and virtual functions.

11. Visitor

Encapsulates operations for object structures using double-dispatch, suitable for tasks like syntax tree traversal.

Monday, March 25, 2024

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 implementing a single algorithm directly, a class can be designed to use multiple algorithms interchangeably. The Strategy pattern encapsulates each algorithm inside a separate class, known as a strategy class, allowing them to be switched in and out as required. This design aids in decoupling the algorithm's definition from its usage.
Why C++ Programmers Should Study It
  • Flexibility Allows dynamic swapping of algorithms based on runtime conditions.
  • Encapsulation Encapsulates algorithm variations, making them interchangeable.
  • Maintainability Simplifies maintenance by decoupling algorithm implementation from its context.
  • Scalability Eases addition of new strategies without altering the context.
  • Reusability Facilitates algorithm reuse across different contexts or applications.
  • Testability Enhances testability by isolating the context from the strategy.
  • Design Cleanliness Promotes cleaner design by separating concerns and reducing conditional statements.
The Strategy design pattern implemented in C++. We'll create three classes: Strategy, ConcreteStrategyA, and ConcreteStrategyB. The Strategy class is an interface defining a family of algorithms, while `ConcreteStrategyA` and `ConcreteStrategyB` are concrete implementations of these algorithms. We'll also create a Context class which maintains a reference to a `Strategy` object and allows the client to switch between different strategies dynamically. Let's start with the header files: Strategy.h
// Abstract Strategy class
class Strategy {
public:
    virtual ~Strategy() {}
    virtual void execute() = 0;
};

ConcreteStrategyA.h
#include "Strategy.h"

// Concrete Strategy A class
class ConcreteStrategyA : public Strategy {
public:
    void execute() override;
};
ConcreteStrategyB.h
#include "Strategy.h"

// Concrete Strategy B class
class ConcreteStrategyB : public Strategy {
public:
    void execute() override;
};
Context.h
#include "Strategy.h"

// Context class
class Context {
public:
    Context(Strategy* strategy);
    void setStrategy(Strategy* strategy);
    void executeStrategy();

private:
    Strategy* strategy_;
};

Now let's implement these classes: ConcreteStrategyA.cpp
#include <iostream>
#include "ConcreteStrategyA.h"

void ConcreteStrategyA::execute() {
    std::cout << "Executing Concrete Strategy A\n";
    // Implementation of strategy A
}
ConcreteStrategyB.cpp</b>
#include <iostream>
#include "ConcreteStrategyB.h"

void ConcreteStrategyB::execute() {
    std::cout << "Executing Concrete Strategy B\n";
    // Implementation of strategy B
}
Context.cpp
#include "Context.h"

Context::Context(Strategy* strategy) : strategy_(strategy) {}

void Context::setStrategy(Strategy* strategy) {
    strategy_ = strategy;
}

void Context::executeStrategy() {
    if (strategy_)
        strategy_->execute();
}
And finally,the main.cpp file:
main.cpp
#include <iostream>
#include "ConcreteStrategyA.h"
#include "ConcreteStrategyB.h"
#include "Context.h"

int main() {
    ConcreteStrategyA strategyA;
    ConcreteStrategyB strategyB;
    
    Context context(&strategyA); // Start with strategy A
    context.executeStrategy(); // Output should be "Executing Concrete Strategy A"
    
    context.setStrategy(&strategyB); // Switch to strategy B
    context.executeStrategy(); // Output should be "Executing Concrete Strategy B"
    
    return 0;
}
The order to create the classes in your project would be:

1. Strategy
2. ConcreteStrategyA
3. ConcreteStrategyB
4. Context

When you run the code, you should see the output:
Executing Concrete Strategy A
Executing Concrete Strategy B>
This demonstrates the Strategy design pattern, where the behavior of the `Context` object can be changed dynamically by switching between different `Strategy` objects.

Monday, March 18, 2024

The State Design Pattern a Behavioral Pattern using PHP

Why PHP Programmers Should Study the State Design Pattern:
Simplified MaintenanceEnables easier updates and bug fixes by localizing state behavior.
Enhanced Scalability Facilitates adding new states and behaviors without modifying existing code.
Improved Readability Makes complex state logic more understandable and organized.
Flexibility in Development Offers a flexible foundation for evolving application requirements and features.
Reusability Across Projects Promotes reusing state-specific logic in different parts of the application or in future projects.
Efficient State Management Streamlines handling of state transitions and associated actions, improving performance.
Encourages Good Practices Fosters use of design principles and patterns, improving overall code quality and architectur

1. State.php (The Abstract State)
Stateis an abstract class that serves as a blueprint for all possible states the context could be in.

Attributes:
$context: This attribute holds a reference to the Context class. This allows each concrete state to interact and potentially change the current state of the context.

Methods:
- setContext(Context $context): Allows setting a reference to the Context object for a state. This is essential for any concrete state that wishes to transition the context to another state.
- handle1(): An abstract method which defines how this state responds to the request1 method call on the context. Concrete states will provide their own implementation.
- handle2(): Similarly, an abstract method defining the behavior for the request2 method call on the context. Again, the concrete states will provide specific implementations.
abstract class State
{
    /**
     * @var Context
     */
    protected $context;

    public function setContext(Context $context)
    {
        $this->context = $context;
    }

    abstract public function handle1(): void;

    abstract public function handle2(): void;
}

2. Context.php (The Context)
Context is the main class in the State pattern. It holds a reference to the current state and allows clients to trigger state transitions and behaviors.

Attributes:
- $state: This holds the current state of the context. It's of type State, so it could be an instance of any of the concrete state classes.

Methods - __construct(State $state): The constructor initializes the context with a given state and sets it using the transitionTo method.
- transitionTo(State $state): This method allows the context to change its current state. It sets the new state, updates the state's context reference, and then logs the transition.
- request1() and request2(): These methods delegate calls to the current state's respective handle1 and handle2 methods. This is where the actual state-based behavior takes place.
class Context
{
    /**
     * @var State A reference to the current state of the Context.
     */
    private $state;

    public function __construct(State $state)
    {
        $this->transitionTo($state);
    }

    /**
     * The Context allows changing the State object at runtime.
     */
    public function transitionTo(State $state): void
    {
        echo "Context: Transition to " . get_class($state) . ".<br/>";
        $this->state = $state;
        $this->state->setContext($this);
    }

    /**
     * The Context delegates part of its behavior to the current State object.
     */
    public function request1(): void
    {
        $this->state->handle1();
    }

    public function request2(): void
    {
        $this->state->handle2();
    }
}

ConcreteStateA.php & ConcreteStateB.php (The Concrete States)

These classes represent specific states the context can be in. They extend the abstract State class and provide concrete implementations for its abstract methods.
ConcreteStateA: Methods:
- handle1(): Outputs that it's handling request1 and then changes the state of the context to ConcreteStateB. - handle2(): Outputs that it's handling request2 but doesn't change the state. ConcreteStateB: Methods: - handle1(): Outputs that it's handling request1 but doesn't change the state. - handle2(): Outputs that it's handling request2 and then changes the state of the context back to ConcreteStateA.
ConcreteStateA.php
class ConcreteStateA extends State
{
    public function handle1(): void
    {
        echo "ConcreteStateA handles request1.<br/>";
        echo "ConcreteStateA wants to change the state of the context.<br/>";
        $this->context->transitionTo(new ConcreteStateB);
    }

    public function handle2(): void
    {
        echo "ConcreteStateA handles request2.<br/>";
    }
}
ConcreteStateB.php
class ConcreteStateB extends State
{
    public function handle1(): void
    {
        echo "ConcreteStateB handles request1.<br/>";
    }

    public function handle2(): void
    {
        echo "ConcreteStateB handles request2.<br/>";
        echo "ConcreteStateB wants to change the state of the context.<br/>";
        $this->context->transitionTo(new ConcreteStateA);
    }
}
4. index.php (Client Code)
This script sets everything in motion. It includes all necessary files and then: - Creates a new Context object with an initial state of ConcreteStateA
. - Calls request1() on the context, triggering ConcreteStateA's handle1() method.
- Calls request2() on the context, which at this point triggers ConcreteStateB's handle2() method due to the state transition in the previous step.

In essence, the design pattern shown here allows the `Context` class to change its behavior when its internal state changes, without modifying the class itself. The behavior for each state is encapsulated in the concrete state classes. The context simply delegates the requests to these state objects.
index.php
include_once ('Context.php');
include_once ('State.php');
include_once ('ConcreteStateA.php');
include_once ('ConcreteStateB.php');

/**
 * The client code.
 */
$context = new Context(new ConcreteStateA);
$context->request1();
$context->request2();

what is shown in the browser:
Context: Transition to ConcreteStateA.
ConcreteStateA handles request1.
ConcreteStateA wants to change the state of the context.
Context: Transition to ConcreteStateB.
ConcreteStateB handles request2.
ConcreteStateB wants to change the state of the context.
Context: Transition to ConcreteStateA.

Monday, March 11, 2024

The Observer Design Pattern using Java

The Observer Design Pattern is a behavioral pattern that sets up a one-to-many dependency between objects. When the state of one object (known as the "Subject") changes, all of its dependents ("Observers") are notified and updated automatically. The Subject maintains a list of its Observers and offers mechanisms to add, remove, or notify them. In this pattern, there are mainly four classes: Subject, ConcreteSubject, Observer, and ConcreteObserver. Each class serves a specific role in implementing the pattern. Here's an example of how you can structure and implement the Observer design pattern in Java:

1. Subject.java

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

public interface Subject {
    void addObserver(Observer observer);
    void removeObserver(Observer observer);
    void notifyObservers();
}
The `Subject` interface defines methods that allow objects to register as observers, remove themselves as observers, and notify all observers when a change occurs.

2. ConcreteSubject.java

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

public class ConcreteSubject implements Subject {
    private List<Observer> observers = new ArrayList<>();
    private int state;

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
        notifyObservers();
    }

    @Override
    public void addObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update();
        }
    }
}
`ConcreteSubject` is a class that implements the `Subject` interface. It maintains a list of observers and notifies them when its state changes.

3. Observer.java

public interface Observer {
    void update();
}
The `Observer` interface declares an `update` method that concrete observers will implement to respond to changes in the subject's state.

4. ConcreteObserver.java

public class ConcreteObserver implements Observer {
    private String name;
    private ConcreteSubject subject;

    public ConcreteObserver(String name, ConcreteSubject subject) {
        this.name = name;
        this.subject = subject;
        subject.addObserver(this);
    }

    @Override
    public void update() {
        int newState = subject.getState();
        System.out.println(name + " received an update: State is now " + newState);
    }
}
`ConcreteObserver` is a class that implements the `Observer` interface. It registers itself with a `ConcreteSubject` during construction and responds to updates by printing a message.

5. Main.java

public class Main {
    public static void main(String[] args) {
        ConcreteSubject subject = new ConcreteSubject();
        ConcreteObserver observer1 = new ConcreteObserver("Observer 1", subject);
        ConcreteObserver observer2 = new ConcreteObserver("Observer 2", subject);

        subject.setState(10);
        subject.setState(20);
    }
}
In the `Main` class, we create a `ConcreteSubject` and two `ConcreteObserver` instances. We then change the subject's state twice, which triggers notifications to the observers.

Order to create classes:

1. `Subject` interface
2. `ConcreteSubject` class
3. `Observer` interface
4. `ConcreteObserver` class
5. `Main` class
When you run the code, you should see the following output:
Observer 1 received an update: State is now 10
Observer 2 received an update: State is now 10
Observer 1 received an update: State is now 20
Observer 2 received an update: State is now 20
This output demonstrates that both observers are notified and updated when the subject's state change

Thursday, February 01, 2024

The Memento design pattern using C#

The Memento design pattern is all about capturing and storing the current state of an object in a manner that allows it to be restored later on, without breaking the principles of encapsulation.

The Order of Creating Classes:
1. Memento: This stores the internal state of the `Originator` object.
2. Originator: This is the object whose state we want to save and restore. It creates a memento and restores its state from it.
3. Caretaker: It keeps track of multiple mementos. It helps maintain the history of states.


Explanation and Code:

Memento.cs
using System;

public class Memento
{
    private string _state;

    public Memento(string state)
    {
        _state = state;
    }

    public string GetState()
    {
        return _state;
    }
}
This class is responsible for storing the state of the `Originator`. It has a method to retrieve the state.

Originator.cs
public class Originator
{
    private string _state;

    // Set a new state
    public void SetState(string state)
    {
        _state = state;
    }

    // Get current state
    public string GetState()
    {
        return _state;
    }

    // Save state to memento
    public Memento SaveStateToMemento()
    {
        return new Memento(_state);
    }

    // Restore state from memento
    public void GetStateFromMemento(Memento memento)
    {
        _state = memento.GetState();
    }
}
The Originator class can create a snapshot of its current state by using the SaveStateToMemento method. It can also restore its state using a given Memento object.

Caretaker.cs
using System.Collections.Generic;

public class Caretaker
{
    private List<Memento> _mementoList = new List<Memento>();

    public void Add(Memento state)
    {
        _mementoList.Add(state);
    }

    public Memento Get(int index)
    {
        return _mementoList[index];
    }
}
The `Caretaker` maintains a list of memento objects and can add new mementos or retrieve existing ones.

Program.cs
using System;

class Program
{
    static void Main(string[] args)
    {
        Originator originator = new Originator();
        Caretaker caretaker = new Caretaker();

        // Changing and saving states
        originator.SetState("State #1");
        caretaker.Add(originator.SaveStateToMemento());

        originator.SetState("State #2");
        caretaker.Add(originator.SaveStateToMemento());

        originator.SetState("State #3");
        caretaker.Add(originator.SaveStateToMemento());

        originator.SetState("State #4");
        Console.WriteLine("Current State: " + originator.GetState());

        // Restoring previous states
        originator.GetStateFromMemento(caretaker.Get(0));
        Console.WriteLine("First saved State: " + originator.GetState());
        originator.GetStateFromMemento(caretaker.Get(1));
        Console.WriteLine("Second saved State: " + originator.GetState());
    }
}
In Program.cs, we create instances of the Originator and Caretaker classes. We then change the state of the Originator multiple times and save these states using the Caretaker. Finally, we demonstrate restoring the Originator to its previous states. This is a basic implementation of the Memento pattern in C#. The real power comes in when you have complex objects with multiple fields and need to maintain versions of those objects over time.

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

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.

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

The Bridge pattern is a structural design pattern using C++

The Bridge pattern is a structural design pattern that's all about decoupling an abstraction from its implementation so that the two c...