Showing posts with label Decorator. Show all posts
Showing posts with label Decorator. Show all posts

Saturday, January 06, 2024

The Decorator pattern using C++

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

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

#ifndef CONCRETECOMPONENT_H
#define CONCRETECOMPONENT_H

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

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

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

#include "Component.h"

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

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

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

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

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

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

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

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

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

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

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

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

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

Monday, April 26, 2021

Decorator pattern Php

Decorator also known as: Wrapper is a structural design pattern that lets you attach new behaviors to objects by placing these objects inside special wrapper objects that contain the behaviors. Using decorators you can wrap objects countless number of times since both target objects and decorators follow the same interface. The resulting object will get a stacking behavior of all wrappers.
This example illustrates the structure of the Decorator design pattern and focuses on the following questions:
  1. What classes does it consist of?
  2. What roles do these classes play?
  3. In what way the elements of the pattern are related?
Let's start by createing the Component.php file interface.
interface Component
{
    public function operation(): string;
}
Let's create a class called Decorator.php and let it be implemented by Component.php. The Decorator delegates all work to the wrapped component.
class Decorator implements Component
{
    protected $component;

    public function __construct(Component $component)
    {
        $this->component = $component;
    }

    public function operation(): string
    {
        return $this->component->operation();
    }
}
Let's also create a Concrete Component and have implemt the Component.php class. We call our compnent ConcreteDecoratorA. Decorators may call parent implementation of the operation, instead of calling the wrapped object directly. This approach simplifies extension of decorator classes.
class ConcreteDecoratorA extends Decorator
{
    public function operation(): string
    {
        return "ConcreteDecoratorA(" . parent::operation() . ")";
    }
}
Let's now create a ConcreteDecoratorB.php class file. Like ConcreteDecoratorA it too is exteded with the Decorator.php class
class ConcreteDecoratorB extends Decorator
{
    public function operation(): string
    {
        return "ConcreteDecoratorB(" . parent::operation() . ")";
    }
}
Let's now goto the index.php file at the top we have the includes.
include_once ('Component.php');
include_once ('ConcreteComponent.php');
include_once ('Decorator.php');
include_once ('ConcreteDecoratorA.php');
include_once ('ConcreteDecoratorB.php');
The client code works with all objects using the Component interface. This way it can stay independent of the concrete classes of components it works with.
function clientCode(Component $component)
{
    // ...

    echo "RESULT: " . $component->operation();

    // ...
}
This way the client code can support both simple components as well as decorated ones.
$simple = new ConcreteComponent;
echo "Client: I've got a simple component:<br/>";
clientCode($simple);
echo "<br/><br/>";
Note how decorators can wrap not only simple components but the other decorators as well.
$decorator1 = new ConcreteDecoratorA($simple);
$decorator2 = new ConcreteDecoratorB($decorator1);
echo "Client: Now I've got a decorated component:
"; clientCode($decorator2);
When we view the the index.php through a browser you should get:
Client: I've got a simple component:
RESULT: ConcreteComponent

Client: Now I've got a decorated component:
RESULT: ConcreteDecoratorB(ConcreteDecoratorA(ConcreteComponent))

The Ray Code is AWESOME!!!
wikipedia

Find Ray on:

facebook
youtube
The Ray Code
Ray Andrade

Saturday, April 24, 2021

Decorator pattern Java

Decorator is a structural pattern that allows adding new behaviors to objects dynamically by placing them inside special wrapper objects. Decorator can be recognized by creation methods or constructor that accept objects of the same class or interface as a current class. This example shows how you can adjust the behavior of an object without changing its code. Initially, the business logic class could only read and write data in plain text. Then we created several small wrapper classes that add new behavior after executing standard operations in a wrapped object. The first wrapper encrypts and decrypts data, and the second one compresses and extracts data. You can even combine these wrappers by wrapping one decorator with another. Let's create a package called decorators. Inside this pacage we add our code. We start by creating an interface.
public interface DataSource {
    void writeData(String data);
    String readData();
}
Now let's create some classes for our demonstration. We start with a class called FileDataSource: FileDataSource is extended with the DataSource interface.
import java.io.*;

public class FileDataSource implements DataSource {
    private String name;

    public FileDataSource(String name) {
        this.name = name;
    }

    @Override
    public void writeData(String data) {
        File file = new File(name);
        try (OutputStream fos = new FileOutputStream(file)) {
            fos.write(data.getBytes(), 0, data.length());
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }

    @Override
    public String readData() {
        char[] buffer = null;
        File file = new File(name);
        try (FileReader reader = new FileReader(file)) {
            buffer = new char[(int) file.length()];
            reader.read(buffer);
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
        return new String(buffer);
    }
}
Let's another class that implements DataSource
public class DataSourceDecorator implements DataSource {
    private DataSource wrappee;

    DataSourceDecorator(DataSource source) {
        this.wrappee = source;
    }

    @Override
    public void writeData(String data) {
        wrappee.writeData(data);
    }

    @Override
    public String readData() {
        return wrappee.readData();
    }
}
Now let's create a class the extends the class DataSourceDecorator we just created
import java.util.Base64;

public class EncryptionDecorator extends DataSourceDecorator {

    public EncryptionDecorator(DataSource source) {
        super(source);
    }

    @Override
    public void writeData(String data) {
        super.writeData(encode(data));
    }

    @Override
    public String readData() {
        return decode(super.readData());
    }

    private String encode(String data) {
        byte[] result = data.getBytes();
        for (int i = 0; i < result.length; i++) {
            result[i] += (byte) 1;
        }
        return Base64.getEncoder().encodeToString(result);
    }

    private String decode(String data) {
        byte[] result = Base64.getDecoder().decode(data);
        for (int i = 0; i < result.length; i++) {
            result[i] -= (byte) 1;
        }
        return new String(result);
    }
}
Now let's create another class that also extends DataSourceDecorator. We call this class CompressionDecorator.
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;

public class CompressionDecorator extends DataSourceDecorator {
    private int compLevel = 6;

    public CompressionDecorator(DataSource source) {
        super(source);
    }

    public int getCompressionLevel() {
        return compLevel;
    }

    public void setCompressionLevel(int value) {
        compLevel = value;
    }

    @Override
    public void writeData(String data) {
        super.writeData(compress(data));
    }

    @Override
    public String readData() {
        return decompress(super.readData());
    }

    private String compress(String stringData) {
        byte[] data = stringData.getBytes();
        try {
            ByteArrayOutputStream bout = new ByteArrayOutputStream(512);
            DeflaterOutputStream dos = new DeflaterOutputStream(bout, new Deflater(compLevel));
            dos.write(data);
            dos.close();
            bout.close();
            return Base64.getEncoder().encodeToString(bout.toByteArray());
        } catch (IOException ex) {
            return null;
        }
    }

    private String decompress(String stringData) {
        byte[] data = Base64.getDecoder().decode(stringData);
        try {
            InputStream in = new ByteArrayInputStream(data);
            InflaterInputStream iin = new InflaterInputStream(in);
            ByteArrayOutputStream bout = new ByteArrayOutputStream(512);
            int b;
            while ((b = iin.read()) != -1) {
                bout.write(b);
            }
            in.close();
            iin.close();
            bout.close();
            return new String(bout.toByteArray());
        } catch (IOException ex) {
            return null;
        }
    }
}
Lets put this all together in the Demo class
public class Demo {
    public static void main(String[] args) {
        String salaryRecords = "Name,Salary\nJohn Smith,100000\nSteven Jobs,912000";
        DataSourceDecorator encoded = new CompressionDecorator(
                new EncryptionDecorator(
                        new FileDataSource("out/OutputDemo.txt")));
        encoded.writeData(salaryRecords);
        DataSource plain = new FileDataSource("out/OutputDemo.txt");

        System.out.println("- Input ----------------");
        System.out.println(salaryRecords);
        System.out.println("- Encoded --------------");
        System.out.println(plain.readData());
        System.out.println("- Decoded --------------");
        System.out.println(encoded.readData());
    }
}
When we compile and run we should get:
- Input ----------------
Name,Salary
John Smith,100000
Steven Jobs,912000
- Encoded --------------
Zkt7e1Q5eU8yUm1Qe0ZsdHJ2VXp6dDBKVnhrUHtUe0sxRUYxQkJIdjVLTVZ0dVI5Q2IwOXFISmVUMU5rcENCQmdxRlByaD4+
- Decoded --------------
Name,Salary
John Smith,100000
Steven Jobs,912000

The Ray Code is AWESOME!!!
wikipedia

Find Ray on:

facebook
youtube
The Ray Code
Ray Andrade

Friday, April 23, 2021

Decorator pattern c#

The Decorator is a structural pattern that allows adding new behaviors to objects dynamically by placing them inside special wrapper objects. Using decorators you can wrap objects countless number of times since both target objects and decorators follow the same interface. The resulting object will get a stacking behavior of all wrappers. This example illustrates the structure of the Decorator 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 the elements of the pattern are related?
The Component should be public abstract all others will be abstract only. The base Component interface defines operations that can be altered by decorators.
public abstract class Component
{
    public abstract string Operation();
}
Concrete Components provide default implementations of the operations. There might be several variations of these classes. The Decorator delegates all work to the wrapped component.
class ConcreteComponent : Component
{
    public override string Operation()
    {
        return "ConcreteComponent";
     }
}
The base Decorator class follows the same interface as the other components. The primary purpose of this class is to define the wrapping interface for all concrete decorators. The default implementation of the wrapping code might include a field for storing a wrapped component and the means to initialize it.
abstract class Decorator : Component
{
    protected Component _component;

    public Decorator(Component component)
    {
        this._component = component;
    }

    public void SetComponent(Component component)
    {
        this._component = component;
    }

    public override string Operation()
    {
        if (this._component != null)
        {
            return this._component.Operation();
        }
        else
        {
            return string.Empty;
        }
    }
}
Decorators may call parent implementation of the operation, instead of calling the wrapped object directly. This approach simplifies extension of decorator classes. Concrete Decorators call the wrapped object and alter its result in some way.
class ConcreteDecoratorA : Decorator
{
    public ConcreteDecoratorA(Component comp) : base(comp)
    {
    }

    public override string Operation()
    {
        return $"ConcreteDecoratorA({base.Operation()})";
    }
}
Decorators can execute their behavior either before or after the call to a wrapped object.
class ConcreteDecoratorB : Decorator
{
    public ConcreteDecoratorB(Component comp) : base(comp)
    {  }

    public override string Operation()
    {
        return $"ConcreteDecoratorB({base.Operation()})";
    }
}
The client code works with all objects using the Component interface. This way it can stay independent of the concrete classes of components it works with.
 public class Client
{
    public void ClientCode(Component component)
    {
        Console.WriteLine("RESULT: " + component.Operation());
    }
}
Note how decorators can wrap not only simple components but the other decorators as well.
class Program
{
    static void Main(string[] args)
    {
        Client client = new Client();

        var simple = new ConcreteComponent();
        Console.WriteLine("Client: I get a simple component:");
        client.ClientCode(simple);
        Console.WriteLine();

        ConcreteDecoratorA decorator1 = new ConcreteDecoratorA(simple);
        ConcreteDecoratorB decorator2 = new ConcreteDecoratorB(decorator1);
        Console.WriteLine("Client: Now I've got a decorated component:");
        client.ClientCode(decorator2);
    }
}
Let's compile and run. We get:
Client: I get a simple component:
RESULT: ConcreteComponent

Client: Now I've got a decorated component:
RESULT: ConcreteDecoratorB(ConcreteDecoratorA(ConcreteComponent))

The Ray Code is AWESOME!!!
wikipedia

Find Ray on:

facebook
youtube
The Ray Code
Ray Andrade

Thursday, April 22, 2021

Decorator pattern c++

Decorator is a structural pattern that allows adding new behaviors to objects dynamically by placing them inside special wrapper objects. This example illustrates the structure of the Decorator 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 the elements of the pattern are related?
The base Component interface defines operations that can be altered by decorators.
#include <iostream>

class Component {
public:
    virtual ~Component() {}
    virtual std::string Operation() const = 0;
};
Concrete Components provide default implementations of the operations. There might be several variations of these classes.
#include "Component.h"

class ConcreteComponent : public Component {
public:
    std::string Operation() const override {
        return "ConcreteComponent";
    }
};
The base Decorator class follows the same interface as the other components. The primary purpose of this class is to define the wrapping interface for all concrete decorators. The default implementation of the wrapping code might include a field for storing a wrapped component and the means to initialize it. The Decorator delegates all work to the wrapped component.
#include "Component.h"

class Decorator : public Component {
protected:
    Component* component_;

public:
    Decorator(Component* component) : component_(component) {
    }

    std::string Operation() const override {
        return this->component_->Operation();
    }
};
Decorators may call parent implementation of the operation, instead of calling the wrapped object directly. This approach simplifies extension of decorator classes. Let's create a decorator called ConcreteDecoratorA
#include "Decorator.h"

class ConcreteDecoratorA : public Decorator {
public:
    ConcreteDecoratorA(Component* component) : Decorator(component) {
    }
    std::string Operation() const override {
        return "ConcreteDecoratorA(" + Decorator::Operation() + ")";
    }
};
Let's create another decorator called ConcreteDecoratorB. Decorators can execute their behavior either before or after the call to a wrapped object.
#include "Decorator.h"

class ConcreteDecoratorB : public Decorator {
public:
    ConcreteDecoratorB(Component* component) : Decorator(component) {
    }

    std::string Operation() const override {
        return "ConcreteDecoratorB(" + Decorator::Operation() + ")";
    }
};
This way the client code can support both simple components as well as decorated ones. The client code works with all objects using the Component interface. This way it can stay independent of the concrete classes of components it works with. Note how decorators can wrap not only simple components but the other decorators as well.
#include "ConcreteComponent.h"
#include "ConcreteDecoratorA.h"
#include "ConcreteDecoratorB.h"

void ClientCode(Component* component) {
    // ...
    std::cout << "RESULT: " << component->Operation();
    // ...
}

int main() {

    Component* simple = new ConcreteComponent;
    std::cout << "Client: I've got a simple component:\n";
    ClientCode(simple);
    std::cout << "\n\n";
    
    Component* decorator1 = new ConcreteDecoratorA(simple);
    Component* decorator2 = new ConcreteDecoratorB(decorator1);
    std::cout << "Client: Now I've got a decorated component:\n";
    ClientCode(decorator2);
    std::cout << "\n";

    delete simple;
    delete decorator1;
    delete decorator2;

    return 0;
}
Now let's compile and run, we should get:
Client: I've got a simple component:
RESULT: ConcreteComponent

Client: Now I've got a decorated component:
RESULT: ConcreteDecoratorB(ConcreteDecoratorA(ConcreteComponent))

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