Friday, April 09, 2021

Adapter design pattern c#

This example illustrates the structure of the Adapter design pattern. It focuses on answering these questions:
  • What classes does it consist of?
  • What roles do these classes play?
  • In what way the elements of the pattern are related?
We start with by createing a file called Adaptee. The Adaptee contains some useful behavior, but its interface is incompatible with the existing client code. The Adaptee needs some adaptation before the client code can use it.
class Adaptee
{
   public string GetSpecificRequest()
   {
       return "Specific request.";
   }
}
Next we create the interface ITarget The Target defines the domain-specific interface used by the client code.
public interface ITarget
{
   string GetRequest();
}
The Adapter class will br extended with the ITarget interface. The Adapter makes the Adaptee's interface compatible with the ITarget's interface.
class Adapter : ITarget
{
   private readonly Adaptee _adaptee;

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

   public string GetRequest()
   {
       return $"This is '{this._adaptee.GetSpecificRequest()}'";
   }
}
We put this all together in the Main method in the Program class file.
static void Main(string[] args)
{
   Adaptee adaptee = new Adaptee();
   ITarget target = new Adapter(adaptee);

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

   Console.WriteLine(target.GetRequest());
}
When we compile and run we should get:
Adaptee interface is incompatible with the client.
But with adapter client can call it's method.
This is 'Specific request.'

The Ray Code is AWESOME!!!
wikipedia

Find Ray on:

facebook
youtube
The Ray Code
Ray Andrade

Wednesday, April 07, 2021

Singleton Design Pattern using Java

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one "single" instance. This is useful when exactly one object is needed to coordinate actions across the system. The term comes from the mathematical concept of a singleton. The Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code. The key idea in this pattern is to make the class itself responsible for controlling its instantiation (that it is instantiated only once). Singleton can be recognized by a static creation method, which returns the same cached object.
 public final class Singleton {
    private static Singleton instance;
    public String value;

    private Singleton(String value) {
        // The following code emulates slow initialization.
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        this.value = value;
    }

    public static Singleton getInstance(String value) {
        if (instance == null) {
            instance = new Singleton(value);
        }
        return instance;
    }
}
When we compile and run we should get.

Let's see how this works by creating a **main** method we put in our **Demo** class.
 
 public class Demo {
    public static void main(String[] args) {
        System.out.println("If you see the same value, then singleton was reused (yay!)" + "\n" +
                "If you see different values, then 2 singletons were created (booo!!)" + "\n\n" +
                "RESULT:" + "\n");
        Singleton singleton = Singleton.getInstance("FOO");
        Singleton anotherSingleton = Singleton.getInstance("BAR");
        System.out.println(singleton.value);
        System.out.println(anotherSingleton.value);
    }
}
If you see the same value, then singleton was reused (yay!) If you see different values, then 2 singletons were created (booo!!) RESULT: FOO FOO
We see that there was only one class.. A lot of developers consider the Singleton pattern an antipattern. That’s why its usage is on the decline in Java code.
The Ray Code is AWESOME!!!
wikipedia

Find Ray on:

facebook
youtube
The Ray Code
Ray Andrade

Tuesday, April 06, 2021

Singleton Design Pattern using C++

Why would we want to use a Singleton? In some programs you would want a single instance of a class, for example a db connection. If you have multiple connections you may have fall into update race proplems or lockups from multiple connections trying to gain access the same db.
An implementation of the singleton pattern must:
  • ensure that only one instance of the singleton class ever exists; and
  • provide global access to that instance.
Typically, this is done by declaring all constructors of the class to be private; and providing a static method that returns a reference to the instance. We start with createing a 'Singleton' class, a .cpp file.
#include <string>

class Singleton
{
    static Singleton* s;
    std::string onlyOne;
    Singleton();
public:

    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;
    ~Singleton();
    static Singleton* getInstance();
    void setSingleton(const std::string &st);
    std::string getSingelton();
};
You need to disable the copy constructor.
Now let's create the .h Singleton header file.
#include <string>
class Singleton
{
    static Singleton* s;
    std::string onlyOne;
    Singleton();
public:
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;
    ~Singleton();
    static Singleton* getInstance();
    void setSingleton(const std::string &st);
    std::string getSingelton();
};
Now let's put this all together in main method in the main.cpp file
#include <iostream>
#include "Singleton.h"

using std::cout;
using std::endl;

int main(int argc, char* argv[] ) {

    cout << "The Ray Code is AWESOME!!" << endl;

    cout << "The value is the " << Singleton::getInstance()->getSingelton() << endl;

    Singleton::getInstance()->setSingleton("Changed Value");
    cout <<"The value is the " << Singleton::getInstance()->getSingelton() << endl;

    return 0;
}
Let's compile and run:
The value is the Original Value
The value is the Changed Value

The Ray Code is AWESOME!!!
wikipedia

Find Ray on:

facebook
youtube
The Ray Code
Ray Andrade

Monday, April 05, 2021

Singleton Design Pattern using Php

With the Singelton design pattern we want to ensure that a class has only one instance, while providing a global access point to this instance. The Singleton's instance is stored in a static field. For this demonstration we make the field is an array, because we'll allow our Singleton to have subclasses. Each item in this array will be an instance of a specific Singleton's subclass. You'll see how this works in a moment.
private static $instances = [];
The Singleton's constructor should always be private to prevent direct construction calls with the new operator.
protected function __construct() { }
Singletons should not be cloneable.
protected function __clone() { }
Singletons should not be restorable from strings.
public function __wakeup()
{
   throw new \Exception("Cannot unserialize a singleton.");
}
This is the static method that controls the access to the singleton's instance. On the first run, it creates a singleton object and places it into the static field. On subsequent runs it returns the clients existing object stored in that static field. This implementation lets you subclass the Singleton class while keeping only one instance of each subclass around.
public static function getInstance(): Singleton
{
    $cls = static::class;
    if (!isset(self::$instances[$cls])) {
       self::$instances[$cls] = new static;
    }
    return self::$instances[$cls];
}
Finally, any singleton should define some business logic which can be executed on its instantiation.
public function someBusinessLogic()
{
    // ...
}
Now let's put this altogether in the index.php. We want to attempt to create two different singleton objects. After we create them, then we will compair them. The Singleton class defines the *GetInstance* method that serves as an alternative to constructor and lets clients access the same instance of this class over and over. The code in the index.php file will be:
include_once ('Singleton.php');

function clientCode()
{
    $s1 = Singleton::getInstance();
    $s2 = Singleton::getInstance();
    if ($s1 === $s2) {
        echo "Singleton works, both variables contain the same instance.";
    } else {
        echo "Singleton failed, variables contain different instances.";
    }
}

Now let's finish this project by making a call to clientCode
clientCode();
Our result when we browse to the index.php is:
Singleton works, both variables contain the same instance.
wikipedia

Find Ray on:

facebook
youtube
The Ray Code
Ray Andrade

Saturday, April 03, 2021

Singleton Design Pattern using C#

With the Singelton design pattern we want to ensure that a class has only one instance, while providing a global access point to this instance. To achieve this let's take a look at some c# code. The Singleton class defines the GetInstance method that serves as an alternative to constructor and lets clients access the same instance of this class over and over. The Singleton class is public
public class Singleton
The Singleton's constructor should always be private to prevent direct construction calls with the new operator.
private Singleton() { }
private static Singleton _instance;
This is the static method that controls the access to the singleton instance. On the first run, it creates a singleton object and places it into the static field. On subsequent runs, it returns the client existing object stored in the static field. It checks to see if the oblect is null, not createded yet. If the object is not null that means the Singelton was created and the previouly created object is returned.
public static Singleton GetInstance()
{
    if (_instance == null)
    {
        _instance = new Singleton();
    }
    return _instance;
}
Finally, any singleton should define some business logic, which can be executed on its instance. Here is our example:
public static void someBusinessLogic()
{
   // ...put some logic here
}
Let's put this together in the Program.cs. We want to create two different singleton objects. And then we will compair them.
static void Main(string[] args)
{
    Singleton s1 = Singleton.GetInstance();
    Singleton s2 = Singleton.GetInstance();

     if (s1 == s2)
     {
        Console.WriteLine("Singleton works, both variables contain the same instance.");
     }
     else
     {
         Console.WriteLine("Singleton failed, variables contain different instances.");
     }
}
Let's compile and run. We get
Singleton works, both variables contain the same instance.
wikipedia

Find Ray on:

facebook
youtube
The Ray Code
Ray Andrade

Friday, April 02, 2021

Prototype Design Pattern using Php

Let's start by added a php class file we call Prototype.php. PHP has built-in cloning support. We can clone an object without defining any special methods as long as the object has fields of primitive types. Fields containing objects retain their references in a cloned object. Therefore, in some cases, you might want to clone those referenced objects as well to grt a deeper copy. You can do this in a special __clone() method.
class Prototype
{
    public $primitive;
    public $component;
    public $circularReference;

    public function __clone()
    {
        $this->component = clone $this->component;
        $this->circularReference = clone $this->circularReference;
        $this->circularReference->prototype = $this;
    }
}
Let's create another file we call ComponentWithBackReference.php. Note that the constructor won't be executed during cloning. If you have complex logic inside the constructor, you may need to execute it in the __clone method as well. The code for this file is:
class ComponentWithBackReference
{
    public $prototype;
    public function __construct(Prototype $prototype)
    {
        $this->prototype = $prototype;
    }
}

At the top of the index.php file we add a couple of includes to inclued the files we just created.
include_once ('Prototype.php');
include_once ('ComponentWithBackReference.php');
We now add some client code to our index.php file.
function clientCode()
{
    $p1 = new Prototype;
    $p1->primitive = 245;
    $p1->component = new \DateTime;
    $p1->circularReference = new ComponentWithBackReference($p1);

    $p2 = clone $p1;
    if ($p1->primitive === $p2->primitive) {
        echo "Primitive field values have been carried over to a clone. Yay!<br/>";
    } else {
        echo "Primitive field values have not been copied. Booo!<br/>";
    }
    if ($p1->component === $p2->component) {
        echo "Simple component has not been cloned. Booo!<br/>";
    } else {
        echo "Simple component has been cloned. Yay!<br/>";
    }

    if ($p1->circularReference === $p2->circularReference) {
        echo "Component with back reference has not been cloned. Booo!\n";
    } else {
        echo "Component with back reference has been cloned. Yay!\n";
    }

    if ($p1->circularReference->prototype === $p2->circularReference->prototype) {
        echo "Component with back reference is linked to original object. Booo!\n";
    } else {
        echo "Component with back reference is linked to the clone. Yay!\n";
    }
}
add:
clientCode();
to run this piece of code. Our result is:
Primitive field values have been carried over to a clone. Yay!
Simple component has been cloned. Yay!
Component with back reference has been cloned. Yay! Component with back reference is linked to the clone. Yay!
Tell a friend "The Ray Code is AWESOME!!!" wikipedia
----------------------------------------------------------------------------------------------------
Find Ray on:
facebook
youtube
The Ray Code
Ray Andrade

Thursday, April 01, 2021

Prototype Design Pattern using Java

Let’s take a look at how the Prototype can be implemented without the standard Cloneable interface. The first thing we do is create a package to place our class files. The name of this package we will call shapes. Now let's add an interface we call Shape. Shape will be an abstract class. The code for this abstract class will be
public abstract class Shape {
    public int x;
    public int y;
    public String color;
    public Shape() {
    }
    public Shape(Shape target) {
        if (target != null) {
            this.x = target.x;
            this.y = target.y;
            this.color = target.color;
        }
    }
    public abstract Shape clone();
    @Override
    public boolean equals(Object object2) {
        if (!(object2 instanceof Shape)) return false;
        Shape shape2 = (Shape) object2;
        return shape2.x == x && shape2.y == y && Objects.equals(shape2.color, color);
    }
}
Let's now create a couple of shapes. We will create a Circle class oblect. And, also we will create a Rectangle. Both the Circle and Rectangle are extended with Shape For the Circle class we have the folloing code:
public class Circle extends Shape{
    public int radius;
    public Circle() {
    }
    public Circle(Circle target) {
        super(target);
        if (target != null) {
            this.radius = target.radius;
        }
    }
    @Override
    public Shape clone() {
        return new Circle(this);
    }
    @Override
    public boolean equals(Object object2) {
        if (!(object2 instanceof Circle) || !super.equals(object2)) return false;
        Circle shape2 = (Circle) object2;
        return shape2.radius == radius;
    }
}
And for the Rectangle the code is:
public class Rectangle extends Shape {
    public int width;
    public int height;
    public Rectangle() {
    }
    public Rectangle(Rectangle target) {
        super(target);
        if (target != null) {
            this.width = target.width;
            this.height = target.height;
        }
    }
    @Override
    public Shape clone() {
        return new Rectangle(this);
    }
    @Override
    public boolean equals(Object object2) {
        if (!(object2 instanceof Rectangle) || !super.equals(object2)) return false;
        Rectangle shape2 = (Rectangle) object2;
        return shape2.width == width && shape2.height == height;
    }
}
Lastly we put this all into static void main method we place in the Demo class file. The code looks like:
public class Demo {
    public static void main(String[] args) {
        System.out.println("hello");
        List<Shape> shapes = new ArrayList<>();
        List<Shape> shapesCopy = new ArrayList<>();
        Circle circle = new Circle();
        circle.x = 10;
        circle.y = 20;
        circle.radius = 15;
        circle.color = "red";
        shapes.add(circle);
        Circle anotherCircle = (Circle) circle.clone();
        shapes.add(anotherCircle);
        Rectangle rectangle = new Rectangle();
        rectangle.width = 10;
        rectangle.height = 20;
        rectangle.color = "blue";
        shapes.add(rectangle);
        cloneAndCompare(shapes, shapesCopy);
    }

    private static void cloneAndCompare(List<Shape> shapes, List<Shape> shapesCopy) {
        for (Shape shape : shapes) {
            shapesCopy.add(shape.clone());
        }
        for (int i = 0; i < shapes.size(); i++) {
            if (shapes.get(i) != shapesCopy.get(i)) {
                System.out.println(i + ": Shapes are different objects (yay!)");
                if (shapes.get(i).equals(shapesCopy.get(i))) {
                    System.out.println(i + ": And they are identical (yay!)");
                } else {
                    System.out.println(i + ": But they are not identical (booo!)");
                }
            } else {
                System.out.println(i + ": Shape objects are the same (booo!)");
            }
        }
    }
}
Compile and run. You should get the following result:
hello
0: Shapes are different objects (yay!)
0: And they are identical (yay!)
1: Shapes are different objects (yay!)
1: And they are identical (yay!)
2: Shapes are different objects (yay!)
2: And they are identical (yay!)
The Ray Code is AWESOME!!! (tell a freiend)
wikipedia
----------------------------------------------------------------------------------------------------
Find Ray on:
facebook
youtube
The Ray Code
Ray Andrade

Python Singleton Design Pattern:

Python Singleton Design Pattern: What It Is and Why Study It The Singleton Design Pattern is a creational design pattern ...