Friday, April 30, 2021

Facade pattern php

The Facade pattern provides a unified interface in a subsystem. The Facade defines a HIGHER level interface easier to use. let’s create 2 classes: SubsystemA and SubsystemB
class SubsystemA
{
    public function operation1(): string
    {
        return "SubsystemA: Ready!<br/>";
    }

    // ...

    public function operationN(): string
    {
        return "SubsystemA: Go!<br/>";
    }
}
class SubsystemB
{
    public function operation1(): string
    {
        return "SubsystemB: Get ready!<br/>";
    }

    // ...

    public function operationZ(): string
    {
        return "SubsystemB: Fire!<br/>";
    }
}
now create class Facade add code: Depending on your application's needs, you can provide the Facade with existing subsystem objects or force the Facade to create them on its own. The Facade's methods are convenient shortcuts to the sophisticated functionality of the subsystems. However, clients get only to a fraction of a subsystem's capabilities.
class Facade
{
    protected $subsystem1;

    protected $subsystem2;

    public function __construct(
        SubsystemA $subsystem1 = null,
        SubsystemB $subsystem2 = null
    ) {
        $this->subsystem1 = $subsystem1 ?: new SubsystemA;
        $this->subsystem2 = $subsystem2 ?: new SubsystemB;
    }

    public function operation(): string
    {
        $result = "Facade initializes subsystems:<br/>";
        $result .= $this->subsystem1->operation1();
        $result .= $this->subsystem2->operation1();
        $result .= "Facade orders subsystems to perform the action:<br/>";
        $result .= $this->subsystem1->operationN();
        $result .= $this->subsystem2->operationZ();

        return $result;
    }
}
last we go to the index page we add includes the file we just created
include_once ('Facade.php');
include_once ('SubsystemA.php');
include_once ('SubsystemB.php');
and add code:
function clientCode(Facade $facade)
{
  echo $facade->operation();
}

$subsystemA = new SubsystemA;
$subsystemB = new SubsystemB;
$facade = new Facade($subsystemA, $subsystemB);
clientCode($facade);
Let's now take a look through a btowser.
Facade initializes subsystems:
SubsystemA: Ready!
SubsystemB: Get ready!
Facade orders subsystems to perform the action:
SubsystemA: Go!
SubsystemB: Fire!
Facade is a structural design pattern that provides a simplified interface to a library, a framework, or any other complex set of classes. I hope you’ve enjoyed this episode Facade design pattern
The Ray Code is AWESOME!!!
wikipedia

Find Ray on:

facebook
youtube
The Ray Code
Ray Andrade

Thursday, April 29, 2021

Facade pattern java

Let's create a package called some_complex_media_library. Inside of this package we add an interface we will call Codec. Now let's add a class we call VideoFile. The code for **VideoFile** will be:
public class VideoFile {
    private String name;
    private String codecType;

    public VideoFile(String name) {
        this.name = name;
        this.codecType = name.substring(name.indexOf(".") + 1);
    }

    public String getCodecType() {
        return codecType;
    }

    public String getName() {
        return name;
    }
}
Now let's create a couple of classes that will *implement* Codec, MPEG4CompressionCodec and OggCompressionCodec.
public class MPEG4CompressionCodec implements Codec {
    public String type = "mp4";

}
And for OggCompressionCodec we have:
public class OggCompressionCodec implements Codec {
    public String type = "ogg";
}
Let also add a **CodecFactory** class.
public class CodecFactory {
    public static Codec extract(VideoFile file) {
        String type = file.getCodecType();
        if (type.equals("mp4")) {
            System.out.println("CodecFactory: extracting mpeg audio...");
            return new MPEG4CompressionCodec();
        }
        else {
            System.out.println("CodecFactory: extracting ogg audio...");
            return new OggCompressionCodec();
        }
    }
}
![Facade](/UMLs/images/Facade/Facade-4.png)
I also want to add a BitrateReader class.
public class BitrateReader {
    public static VideoFile read(VideoFile file, Codec codec) {
        System.out.println("BitrateReader: reading file...");
        return file;
    }

    public static VideoFile convert(VideoFile buffer, Codec codec) {
        System.out.println("BitrateReader: writing file...");
        return buffer;
    }
}
Let me add another class I call **AudioMixer**.
import java.io.File;

public class AudioMixer {
    public File fix(VideoFile result){
        System.out.println("AudioMixer: fixing audio...");
        return new File("tmp");
    }
}
Lastly we'll add a class we call **VideoConversionFacade**
import java.io.File;

public class VideoConversionFacade {
    public File convertVideo(String fileName, String format) {
        System.out.println("VideoConversionFacade: conversion started.");
        VideoFile file = new VideoFile(fileName);
        Codec sourceCodec = CodecFactory.extract(file);
        Codec destinationCodec;
        if (format.equals("mp4")) {
            destinationCodec = new OggCompressionCodec();
        } else {
            destinationCodec = new MPEG4CompressionCodec();
        }
        VideoFile buffer = BitrateReader.read(file, sourceCodec);
        VideoFile intermediateResult = BitrateReader.convert(buffer, destinationCodec);
        File result = (new AudioMixer()).fix(intermediateResult);
        System.out.println("VideoConversionFacade: conversion completed.");
        return result;
    }
}
Now let's create a facade packabge. Inside this package we add a VideoConversionFacade class:
import java.io.File;

public class VideoConversionFacade {
    public File convertVideo(String fileName, String format) {
        System.out.println("VideoConversionFacade: conversion started.");
        VideoFile file = new VideoFile(fileName);
        Codec sourceCodec = CodecFactory.extract(file);
        Codec destinationCodec;
        if (format.equals("mp4")) {
            destinationCodec = new OggCompressionCodec();
        } else {
            destinationCodec = new MPEG4CompressionCodec();
        }
        VideoFile buffer = BitrateReader.read(file, sourceCodec);
        VideoFile intermediateResult = BitrateReader.convert(buffer, destinationCodec);
        File result = (new AudioMixer()).fix(intermediateResult);
        System.out.println("VideoConversionFacade: conversion completed.");
        return result;
    }
}
Now let's put this all together in a Demo class which will have a main method.
import java.io.File;

public class Demo {
    public static void main(String[] args) {
        VideoConversionFacade converter = new VideoConversionFacade();
        File mp4Video = converter.convertVideo("youtubevideo.ogg", "mp4");
        // ...
    }
}
Let's compile this an run it, we should get:
VideoConversionFacade: conversion started.
CodecFactory: extracting ogg audio...
BitrateReader: reading file...
BitrateReader: writing file...
AudioMixer: fixing audio...
VideoConversionFacade: conversion completed.
The Ray Code is AWESOME!!! [Wikipedia](https://en.wikipedia.org/wiki/Decorator_pattern) ---------------------------------------------------------------------------------------------------- Find Ray on: [facebook](https://www.facebook.com/TheRayCode/) [youtube](https://www.youtube.com/user/AndradeRay/) [The Ray Code](https://www.RayAndrade.com) [Ray Andrade](https://www.RayAndrade.org)

Wednesday, April 28, 2021

Facade pattern c#

The Subsystem can accept requests either from the facade or client directly. In any case, to the Subsystem, the Facade is yet another client, and it's not a part of the Subsystem.
public class SubsystemA
{
    public string operation1()
    {
        return "SubsystemA: Ready!\n";
    }
    public string operationN()
    {
        return "SubsystemA: Go!\n";
    }
}
Some facades can work with multiple subsystems at the same time.
public class SubsystemB
{
    public string operation2()
    {
        return "SubsystemB: Get ready!\n";
    }
    public string operationZ()
    {
        return "SubsystemB: Fire!\n";
    }
}

![Factory](/UMLs/images/Facade/Facade-3.png)

The Facade class provides a simple interface to the complex logic of one or several subsystems. The Facade delegates the client requests to the appropriate objects within the subsystem. The Facade is also responsible for managing their lifecycle. All of this shields the client from the undesired complexity of the subsystem. The Facade's methods are convenient shortcuts to the sophisticated functionality of the subsystems. However, clients get only to a fraction of a subsystem's capabilities.
public class Facade
{
    protected SubsystemA SubsystemA;
    
    protected SubsystemB SubsystemB;
    public Facade(SubsystemA subsystemA, SubsystemB subsystemB)
    {
        this.SubsystemA = subsystemA;
        this.SubsystemB = subsystemB;
    }
    public string Operation()
    {
        string result = "Facade initializes subsystems:\n";
        result += this.SubsystemA.operation1();
        result += this.SubsystemB.operation2();
        result += "Facade orders subsystems to perform the action:\n";
        result += this.SubsystemA.operationN();
        result += this.SubsystemB.operationZ();
        return result;
    }
}
The client code works with complex subsystems through a simple interface provided by the Facade. When a facade manages the lifecycle of the subsystem, the client might not even know about the existence of the subsystem. This approach lets you keep the complexity under control.
class Client
{
    public static void ClientCode(Facade facade)
    {
        Console.Write(facade.Operation());
    }
}
The client code may have some of the subsystem's objects already created. In this case, it might be worthwhile to initialize the Facade with these objects instead of letting the Facade create new instances.
static void Main(string[] args)
{
    SubsystemA subsystemA = new SubsystemA();
    SubsystemB subsystemB = new SubsystemB();
    Facade facade = new Facade(subsystemA, subsystemB);
    Client.ClientCode(facade);
}
Now let's compile and run. We should get:
Facade initializes subsystems:
SubsystemA: Ready!
SubsystemB: Get ready!
Facade orders subsystems to perform the action:
SubsystemA: Go!
SubsystemB: Fire!

The Ray Code is AWESOME!!!
wikipedia

Find Ray on:

facebook
youtube
The Ray Code
Ray Andrade

Tuesday, April 27, 2021

Facade pattern c++

Facade is a structural design pattern that provides a simplified (but limited) interface to a complex system of classes, library or framework. This example illustrates the structure of the Facade 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 Subsystem can accept requests either from the facade or client directly. In any case, to the Subsystem, the Facade is yet another client, and it's not a part of the Subsystem.
#include <iostream>

class SystemA {
public:
    std::string OperationA() const {
        return "SystemA: Ready!\n";
    }
    // ...
    std::string OperationN() const {
        return "SystemA: Go!\n";
    }
};
Some facades can work with multiple subsystems at the same time.
#include <iostream>

class SystemB {
public:
    std::string OperationA() const {
        return "SystemB: Get ready!\n";
    }
    // ...
    std::string OperationZ() const {
        return "SystemB: Fire!\n";
    }
};
![Factory](/UMLs/images/Facade/Facade-1.jpg)

The Facade class provides a simple interface to the complex logic of one or several subsystems. The Facade delegates the client requests to the appropriate objects within the subsystem. The Facade is also responsible for managing their lifecycle. All of this shields the client from the undesired complexity of the subsystem. Depending on your application's needs, you can provide the Facade with existing subsystem objects or force the Facade to create them on its own. The Facade's methods are convenient shortcuts to the sophisticated functionality of the subsystems. However, clients get only to a fraction of a subsystem's capabilities.
class Facade {
protected:
    SystemA *system1_;
    SystemB *system2_;
public:
    Facade(
            SystemA *system1 = nullptr,
            SystemB *system2 = nullptr) {
        this->system1_ = system1 ?: new SystemA;
        this->system2_ = system2 ?: new SystemB;
    }
    ~Facade() {
        delete system1_;
        delete system2_;
    }
    std::string Operation() {
        std::string result = "Facade initializes systems:\n";
        result += this->system1_->OperationA();
        result += this->system2_->OperationA();
        result += "Facade orders systems to perform the action:\n";
        result += this->system1_->OperationN();
        result += this->system2_->OperationZ();
        return result;
    }
};
Let's now go to the main.cpp The client code works with complex subsystems through a simple interface provided by the Facade. When a facade manages the lifecycle of the subsystem, the client might not even know about the existence of the subsystem. This approach lets you keep the complexity under control.
#include "Facade.h"

void ClientCode(Facade *facade) {
    // ...
    std::cout << facade->Operation();
    // ...
}
The client code may have some of the system's objects already created. In this case, it might be worthwhile to initialize the Facade with these objects instead of letting the Facade create new instances.
int main() {
    SystemA *system1 = new SystemA;
    SystemB *system2 = new SystemB;
    Facade *facade = new Facade(system1, system2);
    ClientCode(facade);

    delete facade;

    return 0;
}
When we compile and run we get:
Facade initializes systems:
SystemA: Ready!
SystemB: Get ready!
Facade orders systems to perform the action:
SystemA: Go!
SystemB: Fire!

The Ray Code is AWESOME!!!
wikipedia

Find Ray on:

facebook
youtube
The Ray Code
Ray Andrade

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

Wednesday, April 21, 2021

Composite pattern PHP

This example illustrates the structure of the Composite design pattern and focuses on the following questions: What roles do these classes play? In what way the elements of the pattern are related?
  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 can declare an interface for setting and accessing a parent of the component in a tree structure. It can also provide some default implementation for these methods.

In some cases, it would be beneficial to define the child-management operations right in the base Component class. This way, you won't need to expose any concrete component classes to the client code, even during the object tree assembly. The downside is that these methods will be empty for the leaf-level components.

You can provide a method that lets the client code figure out whether a component can bear children. The base Component may implement some default behavior or leave it to concrete classes (by declaring the method containing the behavior as abstract).
abstract class Component
{
    protected $parent;

    public function setParent(Component $parent)
    {
        $this->parent = $parent;
    }

    public function getParent(): Component
    {
        return $this->parent;
    }

    public function add(Component $component): void { }
    public function remove(Component $component): void { }

    public function isComposite(): bool
    {
        return false;
    }

    abstract public function operation(): string;
}
The Composite class represents the complex components that may have children. Usually, the Composite objects delegate the actual work to their children and then sum-up the result. A composite object can add or remove other components (both simple or complex) to or from its child list.

The Composite executes its primary logic in a particular way. It traverses recursively through all its children, collecting and summing their results. Since the composite's children pass these calls to their children and so forth, the whole object tree is traversed as a result.
include_once ('Component.php');

class Composite extends Component
{
    protected $children;

    public function __construct()
    {
        $this->children = new \SplObjectStorage();
    }

    public function add(Component $component): void
    {
        $this->children->attach($component);
        $component->setParent($this);
    }

    public function remove(Component $component): void
    {
        $this->children->detach($component);
        $component->setParent(null);
    }
    public function isComposite(): bool
    {
        return true;
    }

    public function operation(): string
    {
        $results = [];
        foreach ($this->children as $child) {
            $results[] = $child->operation();
        }

        return "Branch(" . implode("+", $results) . ")";
    }
}
The Leaf class represents the end objects of a composition. A leaf can't have any children.

Usually, it's the Leaf objects that do the actual work, whereas Composite objects only delegate to their sub-components.
class Leaf extends Component
{
    public function operation(): string
    {
        return "Leaf";
    }
}
The client code works with all of the components via the base interface. This way the client code can support the simple leaf components as well as the complex composites.
include_once ('Composite.php');
include_once ('Leaf.php');

function clientCode(Component $component)
{
    // ...

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

    // ...
}

$simple = new Leaf();
echo "Client: I've got a simple component:"<br/>";
clientCode($simple);
echo "\n\n";

$tree = new Composite();
$branch1 = new Composite();
$branch1->add(new Leaf());
$branch1->add(new Leaf());
$branch2 = new Composite();
$branch2->add(new Leaf());
$tree->add($branch1);
$tree->add($branch2);
echo "Client: Now I've got a composite tree:"<br/>";
clientCode($tree);
echo "<br/>"<br/>";

Thanks to the fact that the child-management operations are declared in the base Component class, the client code can work with any component, simple or complex, without depending on their concrete classes.
function clientCode2(Component $component1, Component $component2)
{
    // ...

    if ($component1->isComposite()) {
        $component1->add($component2);
    }
    echo "RESULT: " . $component1->operation();

    // ...
}

echo "Client: I don't need to check the components classes even when managing the tree:\n";
clientCode2($tree, $simple);
Now let's run this in a browser and we whould get:
Client: I've got a simple component:
RESULT: Leaf Client: Now I've got a composite tree:
RESULT: Branch(Branch(Leaf+Leaf)+Branch(Leaf))

Client: I don't need to check the components classes even when managing the tree: RESULT: Branch(Branch(Leaf+Leaf)+Branch(Leaf)+Leaf)

The Ray Code is AWESOME!!!
wikipedia

Find Ray on:

facebook
youtube
The Ray Code
Ray Andrade

Tuesday, April 20, 2021

Composite pattern java

In this tutoraial posting we will use the java.awt library.

Composite is a structural design pattern that allows composing objects into a tree-like structure and work with the it as if it was a singular object.

Composite became a pretty popular solution for the most problems that require building a tree structure. Composite’s great feature is the ability to run methods recursively over the whole tree structure and sum up the results.

We will be using the java.awt library in our demo. Let's create a package first. The name of the package will be shapes. Inside of this package we place the *interface* Shape.
import java.awt.*;

public interface Shape {
    int getX();
    int getY();
    int getWidth();
    int getHeight();
    void move(int x, int y);
    boolean isInsideBounds(int x, int y);
    void select();
    void unSelect();
    boolean isSelected();
    void paint(Graphics graphics);
}
Let's also create a base class we call BaseShape and it will implement Shape.
import java.awt.*;

abstract class BaseShape implements Shape {
    public int x;
    public int y;
    public Color color;
    private boolean selected = false;

    BaseShape(int x, int y, Color color) {
        this.x = x;
        this.y = y;
        this.color = color;
    }

    @Override
    public int getX() {
        return x;
    }

    @Override
    public int getY() {
        return y;
    }

    @Override
    public int getWidth() {
        return 0;
    }

    @Override
    public int getHeight() {
        return 0;
    }

    @Override
    public void move(int x, int y) {
        this.x += x;
        this.y += y;
    }

    @Override
    public boolean isInsideBounds(int x, int y) {
        return x > getX() && x < (getX() + getWidth()) &&
                y > getY() && y < (getY() + getHeight());
    }

    @Override
    public void select() {
        selected = true;
    }

    @Override
    public void unSelect() {
        selected = false;
    }

    @Override
    public boolean isSelected() {
        return selected;
    }

    void enableSelectionStyle(Graphics graphics) {
        graphics.setColor(Color.LIGHT_GRAY);

        Graphics2D g2 = (Graphics2D) graphics;
        float dash1[] = {2.0f};
        g2.setStroke(new BasicStroke(1.0f,
                BasicStroke.CAP_BUTT,
                BasicStroke.JOIN_MITER,
                2.0f, dash1, 0.0f));
    }

    void disableSelectionStyle(Graphics graphics) {
        graphics.setColor(color);
        Graphics2D g2 = (Graphics2D) graphics;
        g2.setStroke(new BasicStroke());
    }


    @Override
    public void paint(Graphics graphics) {
        if (isSelected()) {
            enableSelectionStyle(graphics);
        }
        else {
            disableSelectionStyle(graphics);
        }

        // ...
    }
}
Let's create a Dot class. We will also put it in the *shapes* **package**.
import java.awt.*;

public class Dot extends BaseShape {
    private final int DOT_SIZE = 3;

    public Dot(int x, int y, Color color) {
        super(x, y, color);
    }

    @Override
    public int getWidth() {
        return DOT_SIZE;
    }

    @Override
    public int getHeight() {
        return DOT_SIZE;
    }

    @Override
    public void paint(Graphics graphics) {
        super.paint(graphics);
        graphics.fillRect(x - 1, y - 1, getWidth(), getHeight());
    }
}
Let's also add a Circle to our shapes package.
import java.awt.*;

public class Circle extends BaseShape {
    public int radius;

    public Circle(int x, int y, int radius, Color color) {
        super(x, y, color);
        this.radius = radius;
    }

    @Override
    public int getWidth() {
        return radius * 2;
    }

    @Override
    public int getHeight() {
        return radius * 2;
    }

    public void paint(Graphics graphics) {
        super.paint(graphics);
        graphics.drawOval(x, y, getWidth() - 1, getHeight() - 1);
    }
}
Let's also create a Rectangle shape class.
import java.awt.*;

public class Rectangle extends BaseShape {
    public int width;
    public int height;

    public Rectangle(int x, int y, int width, int height, Color color) {
        super(x, y, color);
        this.width = width;
        this.height = height;
    }

    @Override
    public int getWidth() {
        return width;
    }

    @Override
    public int getHeight() {
        return height;
    }

    @Override
    public void paint(Graphics graphics) {
        super.paint(graphics);
        graphics.drawRect(x, y, getWidth() - 1, getHeight() - 1);
    }
}
```

Lastly we'll create a CompoundShape class that will be extended with the BaseShape class.
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CompoundShape extends BaseShape {
    protected List <TheRayCode.composite.shapes.Shape> children = new ArrayList<>();

    public CompoundShape(TheRayCode.composite.shapes.Shape... components) {
        super(0, 0, Color.BLACK);
        add(components);
    }

    public void add(TheRayCode.composite.shapes.Shape component) {
        children.add(component);
    }

    public void add(TheRayCode.composite.shapes.Shape... components) {
        children.addAll(Arrays.asList(components));
    }

    public void remove(TheRayCode.composite.shapes.Shape child) {
        children.remove(child);
    }

    public void remove(TheRayCode.composite.shapes.Shape... components) {
        children.removeAll(Arrays.asList(components));
    }

    public void clear() {
        children.clear();
    }

    @Override
    public int getX() {
        if (children.size() == 0) {
            return 0;
        }
        int x = children.get(0).getX();
        for (TheRayCode.composite.shapes.Shape child : children) {
            if (child.getX() < x) {
                x = child.getX();
            }
        }
        return x;
    }

    @Override
    public int getY() {
        if (children.size() == 0) {
            return 0;
        }
        int y = children.get(0).getY();
        for (TheRayCode.composite.shapes.Shape child : children) {
            if (child.getY() < y) {
                y = child.getY();
            }
        }
        return y;
    }

    @Override
    public int getWidth() {
        int maxWidth = 0;
        int x = getX();
        for (TheRayCode.composite.shapes.Shape child : children) {
            int childsRelativeX = child.getX() - x;
            int childWidth = childsRelativeX + child.getWidth();
            if (childWidth > maxWidth) {
                maxWidth = childWidth;
            }
        }
        return maxWidth;
    }

    @Override
    public int getHeight() {
        int maxHeight = 0;
        int y = getY();
        for (TheRayCode.composite.shapes.Shape child : children) {
            int childsRelativeY = child.getY() - y;
            int childHeight = childsRelativeY + child.getHeight();
            if (childHeight > maxHeight) {
                maxHeight = childHeight;
            }
        }
        return maxHeight;
    }

    @Override
    public void move(int x, int y) {
        for (TheRayCode.composite.shapes.Shape child : children) {
            child.move(x, y);
        }
    }

    @Override
    public boolean isInsideBounds(int x, int y) {
        for (TheRayCode.composite.shapes.Shape child : children) {
            if (child.isInsideBounds(x, y)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void unSelect() {
        super.unSelect();
        for (TheRayCode.composite.shapes.Shape child : children) {
            child.unSelect();
        }
    }

    public boolean selectChildAt(int x, int y) {
        for (Shape child : children) {
            if (child.isInsideBounds(x, y)) {
                child.select();
                return true;
            }
        }
        return false;
    }

    @Override
    public void paint(Graphics graphics) {
        if (isSelected()) {
            enableSelectionStyle(graphics);
            graphics.drawRect(getX() - 1, getY() - 1, getWidth() + 1, getHeight() + 1);
            disableSelectionStyle(graphics);
        }

        for (TheRayCode.composite.shapes.Shape child : children) {
            child.paint(graphics);
        }
    }
}
Let's create an editor package and place in it the ImageEditor class.
import TheRayCode.composite.shapes.CompoundShape;
import TheRayCode.composite.shapes.Shape;

import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class ImageEditor {
    private EditorCanvas canvas;
    private CompoundShape allShapes = new CompoundShape();

    public ImageEditor() {
        canvas = new EditorCanvas();
    }

    public void loadShapes(Shape... shapes) {
        allShapes.clear();
        allShapes.add(shapes);
        canvas.refresh();
    }

    private class EditorCanvas extends Canvas {
        JFrame frame;

        private static final int PADDING = 10;

        EditorCanvas() {
            createFrame();
            refresh();
            addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    allShapes.unSelect();
                    allShapes.selectChildAt(e.getX(), e.getY());
                    e.getComponent().repaint();
                }
            });
        }

        void createFrame() {
            frame = new JFrame();
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);

            JPanel contentPanel = new JPanel();
            Border padding = BorderFactory.createEmptyBorder(PADDING, PADDING, PADDING, PADDING);
            contentPanel.setBorder(padding);
            frame.setContentPane(contentPanel);

            frame.add(this);
            frame.setVisible(true);
            frame.getContentPane().setBackground(Color.LIGHT_GRAY);
        }

        public int getWidth() {
            return allShapes.getX() + allShapes.getWidth() + PADDING;
        }

        public int getHeight() {
            return allShapes.getY() + allShapes.getHeight() + PADDING;
        }

        void refresh() {
            this.setSize(getWidth(), getHeight());
            frame.pack();
        }

        public void paint(Graphics graphics) {
            allShapes.paint(graphics);
        }
    }
}
Now we create a Demo class.
import TheRayCode.composite.editor.ImageEditor;
import TheRayCode.composite.shapes.Circle;
import TheRayCode.composite.shapes.CompoundShape;
import TheRayCode.composite.shapes.Dot;
import TheRayCode.composite.shapes.Rectangle;

import java.awt.*;

public class Demo {
    public static void main(String[] args) {
        System.out.println("The Ray Code is AWESOME!!!");
        ImageEditor editor = new ImageEditor();

        editor.loadShapes(
                new Circle(10, 10, 10, Color.BLUE),

                new CompoundShape(
                        new Circle(110, 110, 50, Color.RED),
                        new Dot(160, 160, Color.RED)
                ),

                new CompoundShape(
                        new Rectangle(250, 250, 100, 100, Color.GREEN),
                        new Dot(240, 240, Color.GREEN),
                        new Dot(240, 360, Color.GREEN),
                        new Dot(360, 360, Color.GREEN),
                        new Dot(360, 240, Color.GREEN)
                )
        );
    }
}
Let's compile and run. We should get:
![Composite](/UMLs/images/Composite/Composite2.png) The Ray Code is AWESOME!!!
The Ray Code is AWESOME!!!
wikipedia

Find Ray on:

facebook
youtube
The Ray Code
Ray Andrade

Monday, April 19, 2021

Composite pattern c#

TheComposite design pattern is a structural design pattern that lets you compose objects into tree structures and then work with those structures as if they were individual objects.

The component interface declares common operations for both simple and complex objects of a particular composition. The base Component class declares common operations for both the simple and complex objects of a composition.

The base Component may implement some default behavior and leave it to concrete classes (by declaring the methods containing the behavior as abstract). In some cases, it would be beneficial to define the child-management operations right in the base Component class. This way, you won't need to expose any concrete component classes to the client code, even during the object tree assembly. The downside is that these methods will be empty for the leaf-level components. You can provide a method that lets the client code figure out whether a component can bear children.
abstract class Component
{
    public Component() { }
    public abstract string Operation();
    public virtual void Add(Component component)
    {
        throw new NotImplementedException();
    }
    public virtual void Remove(Component component)
    {
        throw new NotImplementedException();
    }
    public virtual bool IsComposite()
    {
        return true;
    }
}
The Leaf class represents the end objects of a composition. A leaf can't have any children.

The Leaf is extend by Component. Usually, it's the Leaf objects that do the actual work, whereas Composite objects only delegate to their sub-components.
class Leaf : Component
{
    public override string Operation()
    {
        return "Leaf";
    }
    public override bool IsComposite()
    {
        return false;
    }
}
The Composite class represents the complex components that may have children. It too is extended with the Component class. Usually, the Composite objects delegate the actual work to their children and then *sum-up* the result.

The Composite executes its primary logic in a particular way. It traverses recursively through all its children, collecting and summing their results. Since the composite's children pass these calls to their children and so forth, the *whole* object tree is traversed as a result.
class Composite : Component
{
    protected List<Component> _children = new List<Component>();
    public override void Add(Component component)
    {
        this._children.Add(component);
    }
    public override void Remove(Component component)
    {
         this._children.Remove(component);
    }
    public override string Operation()
    {
        int i = 0;
        string result = "Branch(";
        foreach (Component component in this._children)
        {
            result += component.Operation();
            if (i != this._children.Count - 1)
            {
                result += "+";
            }
            i++;
        }
        return result + ")";
    }
}
The client code works with all of the components via the base interface.

Thanks to the fact that the child-management operations are declared in the base Component class, the client code can work with any component, simple or complex, without depending on their concrete classes.
class Client
{
    public void ClientCode(Component leaf)
    {
        Console.WriteLine($"RESULT: {leaf.Operation()}\n");
    }
    public void ClientCode2(Component component1, Component component2)
    {
        if (component1.IsComposite())
        {
            component1.Add(component2);
        }
            
        Console.WriteLine($"RESULT: {component1.Operation()}");
    }
}
This way the client code can support the simple leaf components well as the complex composites. Let's put this altogether in the Program class.
class Program
{
    static void Main(string[] args)
    {
        Client client = new Client();

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

        Composite tree = new Composite();
        Composite branch1 = new Composite();
        branch1.Add(new Leaf());
        branch1.Add(new Leaf());
        Composite branch2 = new Composite();
        branch2.Add(new Leaf());
        tree.Add(branch1);
        tree.Add(branch2);
        Console.WriteLine("Client: Now I've got a composite tree:");
        client.ClientCode(tree);

        Console.Write("Client: I don't need to check the components classes even when managing the tree:\n");
        client.ClientCode2(tree, leaf);
    }
}
When we compile it and run we should get:
Client: I get a simple component:
RESULT: Leaf

Client: Now I've got a composite tree:
RESULT: Branch(Branch(Leaf+Leaf)+Branch(Leaf))

Client: I don't need to check the components classes even when managing the tree:
RESULT: Branch(Branch(Leaf+Leaf)+Branch(Leaf)+Leaf)

The Ray Code is AWESOME!!!
wikipedia

Find Ray on:

facebook
youtube
The Ray Code
Ray Andrade

Saturday, April 17, 2021

Composite pattern c++

The Composite is a structural design pattern that allows composing objects into a tree-like structure and work with the it as if it was a singular object. Using the Composite pattern makes sense only when the core model of your app can be represented as a tree. The Composite pattern suggests that you work with the objects through a common interface which declares a method for doing some work. The base Component class declares common operations for both simple and complex objects of a composition.
Optionally, the base Component can declare an interface for setting and accessing a parent of the component in a tree structure. It can also provide some default implementation for these methods.
In some cases, it would be beneficial to define the child-management operations right in the base Component class. This way, you won't need to expose any concrete component classes to the client code, even during the object tree assembly. The downside is that these methods will be empty for the leaf-level components.
#include <iostream>

class Component {
protected:
    Component *parent_;

public:
    virtual ~Component() {}
    void SetParent(Component *parent) {
        this->parent_ = parent;
    }
    Component *GetParent() const {
        return this->parent_;
    }
    virtual void Add(Component *component) {}
    virtual void Remove(Component *component) {}
    virtual bool IsComposite() const {
        return false;
    }
    virtual std::string Operation() const = 0;
};
You can provide a method that lets the client code figure out whether a component can bear children. The base Component may implement some default behavior or leave it to concrete classes (by declaring the method containing the behavior as abstract). The Leaf class represents the end objects of a composition. A leaf can't have any children. Usually, it's the Leaf objects that do the actual work, whereas Composite objects only delegate to their sub-components.
class Leaf : Component
{
    public override string Operation()
    {
        return "Leaf";
    }
    public override bool IsComposite()
    {
        return false;
    }
};
The Composite class represents the complex components that may have children. Usually, the Composite objects delegate the actual work to their children and then "sum-up" the result. A composite object can add or remove other components (both simple or complex) to or from its child list. Have in mind that this method removes the pointer to the list but doesn't frees the memory, you should do it manually or better use smart pointers.
#include <list>
#include "Component.h"

class Composite : public Component {
protected:
    std::list<Component *> children_;

public:
    void Add(Component *component) override {
        this->children_.push_back(component);
        component->SetParent(this);
    }
    void Remove(Component *component) override {
        children_.remove(component);
        component->SetParent(nullptr);
    }
    bool IsComposite() const override {
        return true;
    }
The Composite executes its primary logic in a particular way. It traverses recursively through all its children, collecting and summing their results. Since the composite's children pass these calls to their children and so forth, the whole object tree is traversed as a result.
    std::string Operation() const override {
        std::string result;
        for (const Component *c : children_) {
            if (c == children_.back()) {
                result += c->Operation();
            } else {
                result += c->Operation() + "+";
            }
        }
        return "Branch(" + result + ")";
    }
};
The Leaf class represents the end objects of a composition. A leaf can't have any children. Usually, it's the Leaf objects that do the actual work, whereas Composite objects only delegate to their sub-components. Now let's go to the main.cpp The client code works with all of the components via the base interface.
#include "Leaf.h"
#include "Composite.h"
void ClientCode(Component *component) {
    // ...
    std::cout << "RESULT: " << component->Operation();
    // ...
}
Thanks to the fact that the child-management operations are declared in the base Component class, the client code can work with any component, simple or complex, without depending on their concrete classes.
void ClientCode2(Component *component1, Component *component2) {
    if (component1->IsComposite()) {
        component1->Add(component2);
    }
    std::cout << "RESULT: " << component1->Operation();
}
This way the client code can support the simple leaf components...
int main() {
    Component *simple = new Leaf;
    std::cout << "Client: I've got a simple component:\n";
    ClientCode(simple);
    std::cout << "\n\n";
...as well as the complex composites.
    Component *tree = new Composite;
    Component *branch1 = new Composite;

    Component *leaf_1 = new Leaf;
    Component *leaf_2 = new Leaf;
    Component *leaf_3 = new Leaf;
    branch1->Add(leaf_1);
    branch1->Add(leaf_2);
    Component *branch2 = new Composite;
    branch2->Add(leaf_3);
    tree->Add(branch1);
    tree->Add(branch2);
    std::cout << "Client: Now I've got a composite tree:\n";
    ClientCode(tree);
    std::cout << "\n\n";

    std::cout << "Client: I don't need to check the components classes even when managing the tree:\n";
    ClientCode2(tree, simple);
    std::cout << "\n";

    delete simple;
    delete tree;
    delete branch1;
    delete branch2;
    delete leaf_1;
    delete leaf_2;
    delete leaf_3;
    return 0;
}    
Now let's compile and run. We should get: ```run Client: I've got a simple component: RESULT: Leaf Client: Now I've got a composite tree: RESULT: Branch(Branch(Leaf+Leaf)+Branch(Leaf)) Client: I don't need to check the components classes even when managing the tree: RESULT: Branch(Branch(Leaf+Leaf)+Branch(Leaf)+Leaf) ```
The Ray Code is AWESOME!!!
wikipedia

Find Ray on:

facebook
youtube
The Ray Code
Ray Andrade

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

Monday, April 12, 2021

Adapter design pattern Php

We start with class Adaptee. The Adaptee has a message that we can't *currently* read.
class Adaptee
{
   public function specificRequest(): string
   {
      return ".eetpadA eht fo roivaheb laicepS";
   }
}
Next we move to our Target class, which we need to create. We create the Target class with the following code:
class Target
{
   public function request(): string
   {
      return "Target: The default target's behavior.";
   }
}
Next we move to the Adapter. The Adapter will do the translation for use using the strrev utility. We create the Adapter class which will be extended by Target.
class Adapter extends Target
{
    private $adaptee;

    public function __construct(Adaptee $adaptee)
    {
        $this->adaptee = $adaptee;
    }

    public function request(): string
    {
        return "Adapter: (TRANSLATED) " . strrev($this->adaptee->specificRequest());
    }
}
Now let's put this all together in the index.php file. We start by listiing our includes files we just created.
include_once ('Target.php');
include_once ('Adaptee.php');
include_once ('Adapter.php');
The client code supports all classes that follow the Target interface.
function clientCode(Target $target)
{
echo $target->request();
}


echo "Client: I can work just fine with the Target objects:<br/>";
$target = new Target;

clientCode($target);

echo "<br/><br/>";

$adaptee = new Adaptee;
echo "Client: The Adaptee class has a weird interface. See, I don't understand it:<br/>";
echo "Adaptee: " . $adaptee->specificRequest();
echo "<br/><br/>";

echo "Client: But I can work with it via the Adapter:<br/>";
$adapter = new Adapter($adaptee);
clientCode($adapter);

echo "<br/><br/>";
Now if we view our code trough a browser we should see:
Client: I can work just fine with the Target objects:
Target: The default target's behavior.

Client: The Adaptee class has a weird interface. See, I don't understand it:
Adaptee: .eetpadA eht fo roivaheb laicepS

Client: But I can work with it via the Adapter:
Adapter: (TRANSLATED) Special behavior of the Adaptee.

The Ray Code is AWESOME!!!
wikipedia

Find Ray on:

facebook
youtube
The Ray Code
Ray Andrade

Saturday, April 10, 2021

Adapter design pattern java

Our goal is to put a roung peg in a 5 cm radius round hole, two Square holes with widths 2 cm and 20 cm. To our orject we add three packages: adapters, round and square. We start with our RoundPeg and we place it in the round package. RoundPegs are compatible with RoundHoles.
public class RoundPeg {
    private double radius;

    public RoundPeg() {}

    public RoundPeg(double radius) {
        this.radius = radius;
    }

    public double getRadius() {
        return radius;
    }
}
RoundHoles are compatible with RoundPegs. To the round package we also add the class RoundHole
public class RoundHole {
    private double radius;

    public RoundHole(double radius) {
        this.radius = radius;
    }

    public double getRadius() {
        return radius;
    }

    public boolean fits(RoundPeg peg) {
        boolean result;
        result = (this.getRadius() >= peg.getRadius());
        return result;
    }
}
The SquarePegs are not compatible with RoundHoles. But we have to integrate them into our program. To the square package we add the following:
public class SquarePeg {
    private double width;

    public SquarePeg(double width) {
        this.width = width;
    }

    public double getWidth() {
        return width;
    }

    public double getSquare() {
        double result;
        result = Math.pow(this.width, 2);
        return result;
    }
}
Now let's create a SquarePegAdapter class and put it in the adapters package.
import TheRayCode.adapter.example.round.RoundPeg;
import TheRayCode.adapter.example.square.SquarePeg;

public class SquarePegAdapter extends RoundPeg {
    private SquarePeg peg;

    public SquarePegAdapter(SquarePeg peg) {
        this.peg = peg;
    }

    @Override
    public double getRadius() {
        double result;
        // Calculate a minimum circle radius, which can fit this peg.
        result = (Math.sqrt(Math.pow((peg.getWidth() / 2), 2) * 2));
        return result;
    }
}
We now put this all together in the main method in our Demo class.
import TheRayCode.adapter.example.adapters.SquarePegAdapter;
import TheRayCode.adapter.example.round.RoundHole;
import TheRayCode.adapter.example.round.RoundPeg;
import TheRayCode.adapter.example.square.SquarePeg;

public class Demo {
    public static void main(String[] args) {
        // Round fits round, no surprise.
        RoundHole hole = new RoundHole(5);
        RoundPeg rpeg = new RoundPeg(5);
        if (hole.fits(rpeg)) {
            System.out.println("Round peg r5 fits round hole r5.");
        }

        SquarePeg smallSqPeg = new SquarePeg(2);
        SquarePeg largeSqPeg = new SquarePeg(20);
        // hole.fits(smallSqPeg); // Won't compile.

        // Adapter solves the problem.
        SquarePegAdapter smallSqPegAdapter = new SquarePegAdapter(smallSqPeg);
        SquarePegAdapter largeSqPegAdapter = new SquarePegAdapter(largeSqPeg);
        if (hole.fits(smallSqPegAdapter)) {
            System.out.println("Square peg w2 fits round hole r5.");
        }
        if (!hole.fits(largeSqPegAdapter)) {
            System.out.println("Square peg w20 does not fit into round hole r5.");
        }
    }
}
Let's compile and run we should get:
Round peg r5 fits round hole r5.
Square peg w2 fits round hole r5.
Square peg w20 does not fit into round hole r5.

The Ray Code is AWESOME!!!
wikipedia

Find Ray on:

facebook
youtube
The Ray Code
Ray Andrade

The Strategy Design Pattern a Behavioral Pattern using C++

The Strategy Design Pattern is a behavioral design pattern that enables selecting an algorithm's implementation at runtime. Instead of i...