Showing posts with label Bridge. Show all posts
Showing posts with label Bridge. Show all posts

Thursday, April 30, 2026

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 can vary independently. This pattern involves an interface or abstract base class which bridges the functionality from concrete classes.

Components

  1. Abstraction: This is an interface or abstract class that defines operations available to the client. These operations are implemented as delegated calls to the Implementor.
  2. Refined Abstraction: Extends the Abstraction. It provides more specific or varied operations based on the Abstraction.
  3. Implementor: This is also an interface or abstract class that defines the methods for the concrete implementations.
  4. Concrete Implementor: Actual concrete classes that implement the Implementor.

Why It's Important for a C++ Developer

  1. Flexibility: One of the key benefits of the Bridge pattern is flexibility. It separates abstraction layers, allowing independent extension and adaptation. In C++, this helps avoid issues with multiple inheritance by favoring composition.
  2. Avoiding Exponential Class Explosion: Without the Bridge pattern, M operations and N implementations can create M×N classes. With Bridge, this is reduced to M+N.
  3. Enabling Independent Evolution: Abstraction and implementation evolve separately. For example, UI logic can change without affecting platform-specific implementations.
  4. Reusability: Implementation details are isolated and reusable across different abstractions, improving code efficiency.
  5. Principle Adherence: Follows "composition over inheritance," a key principle in object-oriented design, especially important in C++ for maintainability and reduced complexity.

In summary, understanding the Bridge pattern is crucial for a C++ developer because it provides a mechanism to keep abstraction and implementation decoupled, resulting in more modular, maintainable, and flexible software design.

S.W.O.T. Analysis of the Bridge Design Pattern for C++

Strengths

  1. Decoupled Design: Separates abstraction from implementation, making systems more modular and adaptable.
  2. Reusable Components: Enables reuse of implementation classes across multiple abstractions.
  3. Scalability: Simplifies adding new abstractions or implementations without modifying existing code.

Weaknesses

  1. Increased Complexity: Adds abstraction layers, which may complicate smaller systems.
  2. Setup Challenges: Requires careful planning to properly structure abstraction and implementation hierarchies.
  3. Debugging Overhead: Diagnosing issues across multiple layers can be more difficult.

Opportunities

  1. Cross-Platform Development: Ideal for separating platform-specific implementations from core logic.
  2. Graphics Engines: Commonly used in C++ engines to abstract rendering systems like DirectX or OpenGL.
  3. IoT Systems: Fits modular architectures where devices interact with various communication protocols.

Threats

  1. Performance Concerns: Additional abstraction layers may introduce overhead in performance-critical systems.
  2. Overengineering Risks: Can add unnecessary complexity if used in simple scenarios.
  3. Alternative Solutions: Patterns like Adapter or Composite may better fit certain use cases.

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.

Friday, April 16, 2021

Bridge pattern Php

Let's create Implementation
interface Implementation
{
    public function operationImplementation(): string;
}
Now let's create the class Abstraction.
class Abstraction
{
    /**
     * @var Implementation
     */
    protected $implementation;

    public function __construct(Implementation $implementation)
    {
        $this->implementation = $implementation;
    }

    public function operation(): string
    {
        return "Abstraction: Base operation with:
" . $this->implementation->operationImplementation(); } }
Now let's create some Concrete Implementations we call ConcreteImplementationA and ConcreteImplementationB. Both will implement the Implementation interface/class.
class ConcreteImplementationA implements Implementation
{
    public function operationImplementation(): string
    {
        return "ConcreteImplementationA: Here's the result on the platform A.<br/>";
    }
}
And for ConcreteImplementationB.
class ConcreteImplementationB implements Implementation
{
    public function operationImplementation(): string
    {
        return "ConcreteImplementationB: Here's the result on the platform B.<br/>";
    }
}
Let's Extended the Abstraction with the class ExtendedAbstraction.
class ExtendedAbstraction extends Abstraction
{
    public function operation(): string
    {
        return "ExtendedAbstraction: Extended operation with:<br/>" .
            $this->implementation->operationImplementation();
    }
}
Now let's put thie all together in the index.php file. We start with the includes:
include_once ('Abstraction.php');
include_once ('ExtendedAbstraction.php');
include_once ('Implementation.php');
include_once ('ConcreteImplementationA.php');
include_once ('ConcreteImplementationB.php');

Except for the initialization phase, where an Abstraction object gets linked with a specific Implementation object, the client code should only depend on the Abstraction class. This way the client code can support any abstraction implementation combination.
function clientCode(Abstraction $abstraction)
{
    // ...

    echo $abstraction->operation();

    // ...
}
The client code should be able to work with any pre-configured abstraction implementation combination.
$implementation = new ConcreteImplementationA;
$abstraction = new Abstraction($implementation);
clientCode($abstraction);

echo "<br/>";

$implementation = new ConcreteImplementationB;
$abstraction = new ExtendedAbstraction($implementation);
clientCode($abstraction);
When we view our code through a browser we should get:
Abstraction: Base operation with:
ConcreteImplementationA: Here's the result on the platform A.

ExtendedAbstraction: Extended operation with:
ConcreteImplementationB: Here's the result on the platform B

The Ray Code is AWESOME!!!
wikipedia

Find Ray on:

facebook
youtube
The Ray Code
Ray Andrade

Thursday, April 15, 2021

Bridge pattern java

First we create an interface for our devices (TV and Radio). We call it the Device interface and we place it in a package devices.
public interface Device {
    boolean isEnabled();
    void enable();
    void disable();
    int getVolume();
    void setVolume(int percent);
    int getChannel();
    void setChannel(int channel);
    void printStatus();
}
Now let's create the devices. Our first device will be the radio. The Radio needs to implement the Device interface. To comply with this interface we need to @Override some funtions. The code for the Radio slass will be:
public class Radio implements Device {
    private boolean on = false;
    private int volume = 30;
    private int channel = 1;

    @Override
    public boolean isEnabled() {
        return on;
    }

    @Override
    public void enable() {
        on = true;
    }

    @Override
    public void disable() {
        on = false;
    }

    @Override
    public int getVolume() {
        return volume;
    }

    @Override
    public void setVolume(int volume) {
        if (volume > 100) {
            this.volume = 100;
        } else if (volume < 0) {
            this.volume = 0;
        } else {
            this.volume = volume;
        }
    }

    @Override
    public int getChannel() {
        return channel;
    }

    @Override
    public void setChannel(int channel) {
        this.channel = channel;
    }

    @Override
    public void printStatus() {
        System.out.println("------------------------------------");
        System.out.println("| I'm radio.");
        System.out.println("| I'm " + (on ? "enabled" : "disabled"));
        System.out.println("| Current volume is " + volume + "%");
        System.out.println("| Current channel is " + channel);
        System.out.println("------------------------------------\n");
    }
}
The second device we will add to our program will be the TV. Let's add the TV class to the devices package. TV also need to implement the Device interface. The code for TV is:
public class Tv implements Device {
    private boolean on = false;
    private int volume = 30;
    private int channel = 1;

    @Override
    public boolean isEnabled() {
        return on;
    }

    @Override
    public void enable() {
        on = true;
    }

    @Override
    public void disable() {
        on = false;
    }

    @Override
    public int getVolume() {
        return volume;
    }

    @Override
    public void setVolume(int volume) {
        if (volume > 100) {
            this.volume = 100;
        } else if (volume < 0) {
            this.volume = 0;
        } else {
            this.volume = volume;
        }
    }

    @Override
    public int getChannel() {
        return channel;
    }

    @Override
    public void setChannel(int channel) {
        this.channel = channel;
    }

    @Override
    public void printStatus() {
        System.out.println("------------------------------------");
        System.out.println("| I'm TV set.");
        System.out.println("| I'm " + (on ? "enabled" : "disabled"));
        System.out.println("| Current volume is " + volume + "%");
        System.out.println("| Current channel is " + channel);
        System.out.println("------------------------------------\n");
    }
}


Now let's create a paclage for the remotes. To the remotes package we add the Remote interface. The code for this interface is:
public interface Remote {
    void power();
    void volumeDown();
    void volumeUp();
    void channelDown();
    void channelUp();
}
Now let's add a BasicRemote to our progrqam. BasicRemote will use the interface Remote. The code for BasicRemote is:
public class BasicRemote implements Remote {
    protected Device device;

    public BasicRemote() {}

    public BasicRemote(Device device) {
        this.device = device;
    }

    @Override
    public void power() {
        System.out.println("Remote: power toggle");
        if (device.isEnabled()) {
            device.disable();
        } else {
            device.enable();
        }
    }

    @Override
    public void volumeDown() {
        System.out.println("Remote: volume down");
        device.setVolume(device.getVolume() - 10);
    }

    @Override
    public void volumeUp() {
        System.out.println("Remote: volume up");
        device.setVolume(device.getVolume() + 10);
    }

    @Override
    public void channelDown() {
        System.out.println("Remote: channel down");
        device.setChannel(device.getChannel() - 1);
    }

    @Override
    public void channelUp() {
        System.out.println("Remote: channel up");
        device.setChannel(device.getChannel() + 1);
    }
}
Let's add another Remote Controll to our program we will call it the AdvancedRemote class. The AdvancedRemote class will be extended by the BasicRemote. The code for our AdvancedRemote will be:
public class AdvancedRemote extends BasicRemote {
    public AdvancedRemote(Device device) {
        super.device = device;
    }

    public void mute() {
        System.out.println("Remote: mute");
        device.setVolume(0);
    }
}
Now we goto our Demo class (where we have the main method at). There our code looks like
public class Demo {
    public static void main(String[] args) {
        testDevice(new Tv());
        testDevice(new Radio());
    }

    public static void testDevice(Device device) {
        System.out.println("Tests with basic remote.");
        BasicRemote basicRemote = new BasicRemote(device);
        basicRemote.power();
        device.printStatus();

        System.out.println("Tests with advanced remote.");
        AdvancedRemote advancedRemote = new AdvancedRemote(device);
        advancedRemote.power();
        advancedRemote.mute();
        device.printStatus();
    }
}
When we copile all this and run it we should get:
Remote: power toggle
------------------------------------
| I'm TV set.
| I'm enabled
| Current volume is 30%
| Current channel is 1
------------------------------------

Tests with advanced remote.
Remote: power toggle
Remote: mute
------------------------------------
| I'm TV set.
| I'm disabled
| Current volume is 0%
| Current channel is 1
------------------------------------

Tests with basic remote.
Remote: power toggle
------------------------------------
| I'm radio.
| I'm enabled
| Current volume is 30%
| Current channel is 1
------------------------------------

Tests with advanced remote.
Remote: power toggle
Remote: mute
------------------------------------
| I'm radio.
| I'm disabled
| Current volume is 0%
| Current channel is 1
------------------------------------


The Ray Code is AWESOME!!!
wikipedia

Find Ray on:

facebook
youtube
The Ray Code
Ray Andrade

Wednesday, April 14, 2021

Bridge design pattern C#

The Abstraction defines the interface for the control part of the two class hierarchies. It maintains a reference to an object of the Implementation hierarchy and delegates all of the real work to this object.
class Abstraction
{
  protected IImplementation _implementation;
        
  public Abstraction(IImplementation implementation)
  {
       this._implementation = implementation;
  }
        
  public virtual string Operation()
  {
      return "Abstract: Base operation with:\n" + 
             _implementation.OperationImplementation();
  }
}
The Implementation defines the interface for all implementation classes. It doesn't have to match the Abstraction's interface. In fact, the two interfaces can be entirely different. Typically the Implementation interface provides only primitive operations, while the Abstraction defines higher-level operations based on those primitives.
public interface IImplementation
{
   string OperationImplementation();
}
You can extend the Abstraction without changing the Implementation classes.
class ExtendedAbstraction : Abstraction
{
   public ExtendedAbstraction(IImplementation implementation) : base(implementation)
   {
   }
        
   public override string Operation()
   {
       return "ExtendedAbstraction: Extended operation with:\n" +
              base._implementation.OperationImplementation();
   }
}
Each Concrete Implementation corresponds to a specific platform and implements the Implementation interface using that platform's API.
class ConcreteImplementationA : IImplementation
{
   public string OperationImplementation()
   {
       return "ConcreteImplementationA: The result in platform A.\n";
   }
}
class ConcreteImplementationB : IImplementation
{
   public string OperationImplementation()
   {
       return "ConcreteImplementationA: The result in platform B.\n";
   }
}
Except for the initialization phase, where an Abstraction object gets linked with a specific Implementation object, the client code should only depend on the Abstraction class. This way the client code can support any abstraction-implementation combination.
class Client
{
   public void ClientCode(Abstraction abstraction)
   {
       Console.Write(abstraction.Operation());
   }
}
The Client code should be able to work with any pre-configured abstraction-implementation combination.
class Program
{
   static void Main(string[] args)
   {
       Client client = new Client();

       Abstraction abstraction;
       abstraction = new Abstraction(new ConcreteImplementationA());
       client.ClientCode(abstraction);
            
       Console.WriteLine();
            
       abstraction = new ExtendedAbstraction(new ConcreteImplementationB());
       client.ClientCode(abstraction);
   }
}
Let's compile and run. When we run the result will be:
Abstract: Base operation with:
ConcreteImplementationA: The result in platform A.

ExtendedAbstraction: Extended operation with:
ConcreteImplementationA: The result in platform B.

The Ray Code is AWESOME!!!
wikipedia

Find Ray on:

facebook
youtube
The Ray Code
Ray Andrade

Tuesday, April 13, 2021

Bridge design pattern C++

The Builder pattern can be recognized in a class, which has a single creation method and several methods to configure the resulting object. This example illustrates the structure of the Builder design pattern. It focuses on answering these questions:
  1. What classes does it consist of?
  2. What roles do these classes play?
  3. In what way do the elements of the pattern related?
It makes sense to use the Builder pattern only when your products are quite complex and require extensive configuration. Unlike in other creational patterns, different concrete builders can produce unrelated products. In other words, results of various builders may not always follow the same interface. Let's create a class called Product. The code for Product.h will be:
class Product {
public:
    std::vector<std::string> parts_;
    void ListParts()const{
        std::cout << "Product parts: ";
        for (size_t i=0;i<parts_.size();i++){
            if(parts_[i]== parts_.back()){
                std::cout << parts_[i];
            }else{
                std::cout < parts_[i] < ", ";
            }
        }
        std::cout << "\n\n";
    }
};
The Builder interface specifies methods for creating the different parts of the Product objects. The code for the Builder.h is:
class Builder {
public:
    virtual ~Builder(){}
    virtual void ProducePartA() const =0;
    virtual void ProducePartB() const =0;
    virtual void ProducePartC() const =0;

};
The Concrete (Solid) Builder classes follows the Builder interface and provide specific implementations of the building steps. Your program may have several variations of Builders , implemented differently.
class SolidBuilder: public Builder {
private:
    Product* product;
public:
    SolidBuilder(){
        this->Reset();
    }
    ~SolidBuilder(){
        delete product;
    }
    void Reset(){
        this->product= new Product();
    }
    void ProducePartA()const override{
        this->product->parts_.push_back("PartA");
    }
    void ProducePartB()const override{
        this->product->parts_.push_back("PartB");
    }
    void ProducePartC()const override{
        this->product->parts_.push_back("PartC");
    }
    Product* GetProduct() {
        Product* result= this->product;
        this->Reset();
        return result;
    }

};
Now let's create a class called Director. The code for our Director.h will be:
#include "Builder.h"

class Director {
private:
    Builder* builder;
public:
    void set_builder(Builder* builder){
        this->builder=builder;
    }
    void BuildMinimalViableProduct(){
        this->builder->ProducePartA();
    }
    void BuildFullFeaturedProduct(){
        this->builder->ProducePartA();
        this->builder->ProducePartB();
        this->builder->ProducePartC();
    }
};
The last place we go to will be the main method to run our demonstration. Let's add some files to include:
#include <iostream>

#include "Director.h"
#include "SolidBuilder.h"
Then we add some client code:
void ClientCode(Director & director)
{
    SolidBuilder* builder = new SolidBuilder();
    director.set_builder(builder);
    std::cout << "Standard basic product:\n";
    director.BuildMinimalViableProduct();

    Product* p= builder->GetProduct();
    p->ListParts();
    delete p;

    std::cout << "Custom product:\n";
    builder->ProducePartA();
    builder->ProducePartC();
    p=builder->GetProduct();
    p->ListParts();
    delete p;

}
And now let's test this all out in main
int main(){
    Director* director= new Director();
    ClientCode(*director);
    delete director;
    return 0;
}
When we compile and run we should get:
Standard basic product:
Product parts: PartA

Custom product:
Product parts: PartA, PartC


The Ray Code is AWESOME!!!
wikipedia

Find Ray on:

facebook
youtube
The Ray Code
Ray Andrade

JavaScript Command Design Pattern Explained | UML, Code & SWOT Analysis

🕹️ What Is the Command Design Pattern? The Command Design Pattern is one of the 11 Behavioral Design Patterns described ...