Wednesday, March 31, 2021

Prototype Design Pattern using c#

The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. All prototype classes should have a common interface that makes it possible to copy objects even if their concrete classes are unknown. Prototype objects can produce full copies since objects of the same class can access each other’s private fields. This example illustrates the structure of the Prototype 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?
Let's start with creating a Person class.
public class Person
{
    public int Age;
    public DateTime BirthDate;
    public string Name;
    public IdInfo IdInfo;

    public Person ShallowCopy()
    {
       return (Person) this.MemberwiseClone();
    }

    public Person DeepCopy()
    {
        Person clone = (Person) this.MemberwiseClone();
        clone.IdInfo = new IdInfo(IdInfo.IdNumber);
        clone.Name = String.Copy(Name);
        return clone;
     }
}
Let's create another class we call IdInfo. The code for IdInfo will be:
public class IdInfo
{
    public int IdNumber;
    public IdInfo(int idNumber)
    {
       this.IdNumber = idNumber;
    }
}
Now let's put this all together in a Program class.
class Program
{
    static void Main(string[] args)
    {
        Person p1 = new Person();
        p1.Age = 42;
        p1.BirthDate = Convert.ToDateTime("1977-01-01");
        p1.Name = "The Ray Code";
        p1.IdInfo = new IdInfo(123);

        // Perform a shallow copy of p1 and assign it to p2.
        Person p2 = p1.ShallowCopy();
        // Make a deep copy of p1 and assign it to p3.
        Person p3 = p1.DeepCopy();

        // Display values of p1, p2 and p3.
        Console.WriteLine("Original values of p1, p2, p3:");
        Console.WriteLine("   p1 instance values: ");
        DisplayValues(p1);
        Console.WriteLine("   p2 instance values:");
        DisplayValues(p2);
        Console.WriteLine("   p3 instance values:");
        DisplayValues(p3);
        // Change the value of p1 properties and display the values of p1,
        // p2 and p3.
        p1.Age = 32;
        p1.BirthDate = Convert.ToDateTime("1900-01-01");
        p1.Name = "Frank";
        p1.IdInfo.IdNumber = 7878;
        Console.WriteLine("\nValues of p1, p2 and p3 after changes to p1:");
        Console.WriteLine("   p1 instance values: ");
        DisplayValues(p1);
        Console.WriteLine("   p2 instance values (reference values have changed):");
        DisplayValues(p2);
        Console.WriteLine("   p3 instance values (everything was kept the same):");
        DisplayValues(p3);
    }

    public static void DisplayValues(Person p)
    {
        Console.WriteLine("      Name: {0:s}, Age: {1:d}, BirthDate: {2:MM/dd/yy}",
           p.Name, p.Age, p.BirthDate);
            Console.WriteLine("      ID#: {0:d}", p.IdInfo.IdNumber);
    }
}
Let's compile and run our project. We should get:
Original values of p1, p2, p3:
      ID#: 7878
   p1 instance values: 
      Name: The Ray Code, Age: 42, BirthDate: 01/01/77
      ID#: 123
   p2 instance values:
      Name: The Ray Code, Age: 42, BirthDate: 01/01/77
      ID#: 123
   p3 instance values:
      Name: The Ray Code, Age: 42, BirthDate: 01/01/77
      ID#: 123

Values of p1, p2 and p3 after changes to p1:
   p1 instance values: 
      Name: Frank, Age: 32, BirthDate: 01/01/00
   p2 instance values (reference values have changed):
      Name: The Ray Code, Age: 42, BirthDate: 01/01/77
      ID#: 7878
   p3 instance values (everything was kept the same):
      Name: The Ray Code, Age: 42, BirthDate: 01/01/77
      ID#: 123
The Ray code is AWESOME!!!
----------------------------------------------------------------------------------------------------

Wikipedia

Find Ray on:
facebook
youtube
The Ray Code
Ray Andrade

Tuesday, March 30, 2021

Prototype Design Pattern using c++

The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to avoid subclasses of an object creator in the client application, like the factory method pattern does. It is also used to avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application. The Prototype pattern delegates the cloning process to the actual objects that are being cloned. The pattern declares a common interface for all objects that support cloning. This interface lets you clone an object without coupling your code to the class of that object. Usually, such an interface contains just a single clone method. We start by creating an enum to list our types PROTOTYPE_1 and PROTOTYPE_2:
enum Type {
  PROTOTYPE_1 = 0,
  PROTOTYPE_2
};
The example class that has cloning ability. We'll see how the values of field with different types will be cloned.
class Prototype {
 protected:
  string prototype_name_;
  float prototype_field_;

 public:
  Prototype() {}
  Prototype(string prototype_name)
      : prototype_name_(prototype_name) {
  }
  virtual ~Prototype() {}
  virtual Prototype *Clone() const = 0;
  virtual void Method(float prototype_field) {
    this->prototype_field_ = prototype_field;
    std::cout << "Call Method from " << prototype_name_ << " with field : " << prototype_field << std::endl;
  }
};
ConcretePrototype1 is a Sub-Class of Prototype and implement the Clone Method. In this example all data members of Prototype Class are in the Stack. If you have pointers in your properties for ex: String* name_ ,you will need to implement the Copy-Constructor to make sure you have a deep copy from the clone method
class ConcretePrototype1 : public Prototype {
private:
    float concrete_prototype_field1_;

public:
    ConcretePrototype1(std::string prototype_name, float concrete_prototype_field)
            : Prototype(prototype_name), concrete_prototype_field1_(concrete_prototype_field) {
    }

    Prototype *Clone() const override {
        return new ConcretePrototype1(*this);
    }
};
Notice that Clone method return a Pointer to a new ConcretePrototype1 replicate. so, the client (who call the clone method) has the responsability to free that memory. If you have smart pointer knowledge you may prefer to use unique_pointer here.
class ConcretePrototype2 : public Prototype {
private:
    float concrete_prototype_field2_;

public:
    ConcretePrototype2(std::string prototype_name, float concrete_prototype_field)
            : Prototype(prototype_name), concrete_prototype_field2_(concrete_prototype_field) {
    }
    Prototype *Clone() const override {
        return new ConcretePrototype2(*this);
    }
};
In Factory you have two concrete prototypes, one for each concrete prototype class, so each time you want to create a bullet , you can use the existing ones and clone those. Be carefull of free all memory allocated. Again, if you have smart pointers knowelege will be better to use it here.
class Factory {
private:
    std::unordered_map<Type, Prototype *, std::hash<int>> prototypes_;

public:
    Factory() {
        prototypes_[Type::PROTOTYPE_1] = new ConcretePrototype1("PROTOTYPE_1 ", 50.f);
        prototypes_[Type::PROTOTYPE_2] = new ConcretePrototype2("PROTOTYPE_2 ", 60.f);
    }

    ~Factory() {
        delete prototypes_[Type::PROTOTYPE_1];
        delete prototypes_[Type::PROTOTYPE_2];
    }

    Prototype *CreatePrototype(Type type) {
        return prototypes_[type]->Clone();
    }
};
Be carefull of free all memory allocated. Again, if you have smart pointers knowelege will be better to use it here. Notice here that you just need to specify the type of the prototype you want and the method will create from the object with this type. Now we go to main and add some client function
void Client(Factory &prototype_factory) {
    std::cout << "Let's create a Prototype 1\n";

    Prototype *prototype = prototype_factory.CreatePrototype(Type::PROTOTYPE_1);
    prototype->Method(90);
    delete prototype;

    std::cout << "\n";

    std::cout << "Let's create a Prototype 2 \n";

    prototype = prototype_factory.CreatePrototype(Type::PROTOTYPE_2);
    prototype->Method(10);

    delete prototype;
}
Now in the main method we run this Client function.
int main() {
    Factory *prototype_factory = new Factory();
    Client(*prototype_factory);
    delete prototype_factory;

    return 0;
}
When we comile and run this we should get:
Let's create a Prototype 1
Call Method from PROTOTYPE_1  with field : 90

Let's create a Prototype 2 
Call Method from PROTOTYPE_2  with field : 10

Process finished with exit code 0
The Ray code is AWESOME!!!
----------------------------------------------------------------------------------------------------

Wikipedia

Find Ray on:
facebook
youtube
The Ray Code
Ray Andrade

Monday, March 29, 2021

Builder Design Pattern using Java

In this example, the Builder pattern allows a step by step construction of various car models. The example also shows how Builder produces can make different kinds cars using the same `building` steps. The Director controls the order of the construction. It knows which building steps to call to produce this or that car model. It works with builders only via their common interface. This allows the passing of different types of builders to the director. The end result is retrieved from the builder object because the director can’t know the type of resulting product. Only the Builder object knows what does it build exactly. Let's create A package we call components. In components we will place the components need to maka car. The component will be Engine, Transmission, TripComputer and GPSNavigator. The code for those componets will be: For Engine we have:
public class Engine {
    private final double volume;
    private double mileage;
    private boolean started;

    public Engine(double volume, double mileage) {
        this.volume = volume;
        this.mileage = mileage;
    }

    public void on() {
        started = true;
    }

    public void off() {
        started = false;
    }

    public boolean isStarted() {
        return started;
    }

    public void go(double mileage) {
        if (started) {
            this.mileage += mileage;
        } else {
            System.err.println("Cannot go(), you must start engine first!");
        }
    }

    public double getVolume() {
        return volume;
    }

    public double getMileage() {
        return mileage;
    }
}
Next we create an say what type of transmission the car has.
public enum Transmission {
    SINGLE_SPEED, MANUAL, AUTOMATIC, SEMI_AUTOMATIC
}
Let's also look at TripComputer. The code for it will be:
public class TripComputer {

    private Car car;

    public void setCar(Car car) {
        this.car = car;
    }

    public void showFuelLevel() {
        System.out.println("Fuel level: " + car.getFuel());
    }

    public void showStatus() {
        if (this.car.getEngine().isStarted()) {
            System.out.println("Car is started");
        } else {
            System.out.println("Car isn't started");
        }
    }
}
Let's also add a GPSNavigator for good measure. the code for the GPSNavigator is:
public class GPSNavigator {
    private String route;

    public GPSNavigator() {
        this.route = "1234 Main Street Anywhere, USA 10011";
    }

    public GPSNavigator(String manualRoute) {
        this.route = manualRoute;
    }

    public String getRoute() {
        return route;
    }
}
Let's create a package called cars. In cars we have as enum for Type.
public enum Type {
    CITY_CAR, SPORTS_CAR, SUV
}
Now that we have the components to create the cars. We have two types of cars Manual or regular Car. We start with the class Car.
public class Car {
    private final Type type;
    private final int seats;
    private final Engine engine;
    private final Transmission transmission;
    private final TripComputer tripComputer;
    private final GPSNavigator gpsNavigator;
    private double fuel = 0;

    public Car(Type type, int seats, Engine engine, Transmission transmission,
               TripComputer tripComputer, GPSNavigator gpsNavigator) {
        this.type = type;
        this.seats = seats;
        this.engine = engine;
        this.transmission = transmission;
        this.tripComputer = tripComputer;
        this.tripComputer.setCar(this);
        this.gpsNavigator = gpsNavigator;
    }

    public Type getType() {
        return type;
    }

    public double getFuel() {
        return fuel;
    }

    public void setFuel(double fuel) {
        this.fuel = fuel;
    }

    public int getSeats() {
        return seats;
    }

    public Engine getEngine() {
        return engine;
    }

    public Transmission getTransmission() {
        return transmission;
    }

    public TripComputer getTripComputer() {
        return tripComputer;
    }

    public GPSNavigator getGpsNavigator() {
        return gpsNavigator;
    }
}
And a Manual type of car. The code for Manual is:
public class Manual {
    private final Type type;
    private final int seats;
    private final Engine engine;
    private final Transmission transmission;
    private final TripComputer tripComputer;
    private final GPSNavigator gpsNavigator;

    public Manual(Type type, int seats, Engine engine, Transmission transmission,
                  TripComputer tripComputer, GPSNavigator gpsNavigator) {

        this.type = type;
        this.seats = seats;
        this.engine = engine;
        this.transmission = transmission;
        this.tripComputer = tripComputer;
        this.gpsNavigator = gpsNavigator;
    }

    public String print() {
        String info = "";
        info += "Type of car: " + type + "\n";
        info += "Count of seats: " + seats + "\n";
        info += "Engine: volume - " + engine.getVolume() + "; mileage - " + engine.getMileage() + "\n";
        info += "Transmission: " + transmission + "\n";
        if (this.tripComputer != null) {
            info += "Trip Computer: Functional" + "\n";
        } else {
            info += "Trip Computer: N/A" + "\n";
        }
        if (this.gpsNavigator != null) {
            info += "GPS Navigator: Functional" + "\n";
        } else {
            info += "GPS Navigator: N/A" + "\n";
        }
        return info;
    }
}
Now let's create some builders to build our cars. Let's add the package builders and let's also add an interface we called Builder. We place this interface the a *package* we also create called builders. The Builder interface defines all possible ways to configure a product. Here is the code:
public interface Builder {
    void setType(Type type);
    void setSeats(int seats);
    void setEngine(Engine engine);
    void setTransmission(Transmission transmission);
    void setTripComputer(TripComputer tripComputer);
    void setGPSNavigator(GPSNavigator gpsNavigator);
}
Now let's create some car builder CarBuilder and CarManualBuilder. Concrete builders implement steps defined in the common interface. For CarBuilder we have:
public class CarBuilder implements Builder {
    private Type type;
    private int seats;
    private Engine engine;
    private Transmission transmission;
    private TripComputer tripComputer;
    private GPSNavigator gpsNavigator;

    @Override
    public void setType(Type type) {
        this.type = type;
    }

    @Override
    public void setSeats(int seats) {
        this.seats = seats;
    }

    @Override
    public void setEngine(Engine engine) {
        this.engine = engine;
    }

    @Override
    public void setTransmission(Transmission transmission) {
        this.transmission = transmission;
    }

    @Override
    public void setTripComputer(TripComputer tripComputer) {
        this.tripComputer = tripComputer;
    }

    @Override
    public void setGPSNavigator(GPSNavigator gpsNavigator) {
        this.gpsNavigator = gpsNavigator;
    }

    public Car getResult() {
        return new Car(type, seats, engine, transmission, tripComputer, gpsNavigator);
    }
}
Unlike other creational patterns, Builder can construct unrelated products, which don't have the common interface. In this case we build a user manual for a car, using the same steps as we built a car. This allows to produce manuals for specific car models, configured with different features.
public class CarManualBuilder implements Builder{
    private Type type;
    private int seats;
    private Engine engine;
    private Transmission transmission;
    private TripComputer tripComputer;
    private GPSNavigator gpsNavigator;

    @Override
    public void setType(Type type) {
        this.type = type;
    }

    @Override
    public void setSeats(int seats) {
        this.seats = seats;
    }

    @Override
    public void setEngine(Engine engine) {
        this.engine = engine;
    }

    @Override
    public void setTransmission(Transmission transmission) {
        this.transmission = transmission;
    }

    @Override
    public void setTripComputer(TripComputer tripComputer) {
        this.tripComputer = tripComputer;
    }

    @Override
    public void setGPSNavigator(GPSNavigator gpsNavigator) {
        this.gpsNavigator = gpsNavigator;
    }

    public Manual getResult() {
        return new Manual(type, seats, engine, transmission, tripComputer, gpsNavigator);
    }
}
We now create a Director and put it in the director package. Director defines the order of building steps. It works with a builder object through common Builder interface. Therefore it may not know what product is being built.
public class Director {

    public void constructSportsCar(Builder builder) {
        builder.setType(Type.SPORTS_CAR);
        builder.setSeats(2);
        builder.setEngine(new Engine(3.0, 0));
        builder.setTransmission(Transmission.SEMI_AUTOMATIC);
        builder.setTripComputer(new TripComputer());
        builder.setGPSNavigator(new GPSNavigator());
    }

    public void constructCityCar(Builder builder) {
        builder.setType(Type.CITY_CAR);
        builder.setSeats(2);
        builder.setEngine(new Engine(1.2, 0));
        builder.setTransmission(Transmission.AUTOMATIC);
        builder.setTripComputer(new TripComputer());
        builder.setGPSNavigator(new GPSNavigator());
    }

    public void constructSUV(Builder builder) {
        builder.setType(Type.SUV);
        builder.setSeats(4);
        builder.setEngine(new Engine(2.5, 0));
        builder.setTransmission(Transmission.MANUAL);
        builder.setGPSNavigator(new GPSNavigator());
    }
}
Let's put this altogether in the main. We create a public called Demo and in this class we place our main method.
public class Demo {

    public static void main(String[] args) {
        Director director = new Director();

        // Director gets the concrete builder object from the client
        // (application code). That's because application knows better which
        // builder to use to get a specific product.
        CarBuilder builder = new CarBuilder();
        director.constructSportsCar(builder);

        // The final product is often retrieved from a builder object, since
        // Director is not aware and not dependent on concrete builders and
        // products.
        Car car = builder.getResult();
        System.out.println("Car built:\n" + car.getType());


        CarManualBuilder manualBuilder = new CarManualBuilder();

        // Director may know several building recipes.
        director.constructSportsCar(manualBuilder);
        Manual carManual = manualBuilder.getResult();
        System.out.println("\nCar manual built:\n" + carManual.print());
    }

}


Now we are ready to run this program and we get
Car built:
SPORTS_CAR

Car manual built:
Type of car: SPORTS_CAR
Count of seats: 2
Engine: volume - 3.0; mileage - 0.0
Transmission: SEMI_AUTOMATIC
Trip Computer: Functional
GPS Navigator: Functional
The Ray code is AWESOME!!!
----------------------------------------------------------------------------------------------------

Wikipedia

Find Ray on:
facebook
youtube
The Ray Code
Ray Andrade

Saturday, March 27, 2021

Builder Design Pattern using C#

Unlike other creational patterns, Builder doesn’t require products to have a common interface. That makes it possible to produce different products using the same construction process. The Builder pattern can be recognized in a class, which has a single creation method and several methods to configure the resulting object. The Builder interface specifies methods for creating the different parts of the Product objects. We start by building an interface we call IBuilder. The code for the interface will be:
public interface IBuilder
{
   void BuildPartA();
   void BuildPartB();
   void BuildPartC();
}
The Concrete Builder classes follow the Builder interface and provide specific implementations of the building steps. Your program may have several variations of Builders, implemented differently.
public class ConcreteBuilder : IBuilder
{
   private Product _product = new Product();
   public void BuildPartA()
   {
      this._product.Add("PartA1");
   }
   public ConcreteBuilder()
   {
      this.Reset();
   }
   public void BuildPartB()
   {
       this._product.Add("PartB1");
   }
   public void BuildPartC()
  {
      this._product.Add("PartC1");
  }
  public void Reset()
  {
      this._product = new Product();
  }
  public Product GetProduct()
  {
      Product result = this._product;
         this.Reset();
        return result;
   }
}
Concrete Builders are supposed to provide their own methods for retrieving results. That's because various types of builders may create entirely different products that don't follow the same interface. Therefore, such methods cannot be declared in the base Builder interface (at least in a statically typed programming language) Usually, after returning the end result to the client, a builder instance is expected to be ready to start producing another product. That's why it's a usual practice to call the reset method at the end of the GetProduct method body. However, this behavior is not mandatory, and you can make your builders wait for an explicit reset call from the client code before disposing of the previous result. Next we create a Product. 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.
public class Product
{
    private List<object> _parts = new List<object>();
    
    public void Add(string part)
    {
       this._parts.Add(part);
    }
        
    public string ListParts()
    {
       string str = string.Empty;
       for (int i = 0; i < this._parts.Count; i++)
       {
           str += this._parts[i] + ", ";
       }
       str = str.Remove(str.Length - 2); // removing last ",c"
       return "Product parts: " + str + "\n";
    }

}
The Director is only responsible for executing the building steps in a particular sequence. It is helpful when producing products according to a specific order or configuration. Strictly speaking, the Director class is optional, since the client can control builders directly.
public class Director
{
   private IBuilder _builder;
        
   public IBuilder Builder
   {
       set { _builder = value; } 
   }
        
   public void buildMinimalViableProduct()
   {
      this._builder.BuildPartA();
   }
        
   public void buildFullFeaturedProduct()
   {
      this._builder.BuildPartA();
      this._builder.BuildPartB();
      this._builder.BuildPartC();
    }

}
The client code creates a builder object, passes it to the director and then initiates the construction process. The end result is retrieved from the builder object.
internal static class Program
{
   static void Main(string[] args)
   {
      var director = new Director();
      var builder = new ConcreteBuilder();
      director.Builder = builder;
            
       Console.WriteLine("Standard basic product:");
       director.buildMinimalViableProduct();
       Console.WriteLine(builder.GetProduct().ListParts());

       Console.WriteLine("Standard full featured product:");
       director.buildFullFeaturedProduct();
       Console.WriteLine(builder.GetProduct().ListParts());

       // Remember, the Builder pattern can be used without a Director
       // class.
       Console.WriteLine("Custom product:");
       builder.BuildPartA();
       builder.BuildPartC();
       Console.Write(builder.GetProduct().ListParts());
   }
}
. Compile and run and you should get:
Standard basic product:
Product parts: PartA1

Standard full featured product:
Product parts: PartA1, PartB1, PartC1

Custom product:
Product parts: PartA1, PartC1
The Ray code is AWESOME!!! ---------------------------------------------------------------------------------------------------- Wikipedia

Find Ray on:
facebook
youtube
The Ray Code
Ray Andrade

Friday, March 26, 2021

Builder Design Pattern using Php

The Builder pattern can be recognized in a class that has a single creation method and several methods to configure the resulting object. The Builder interface specifies those methods for creating the different parts of a Product. 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:
  • What classes does it consist of?
  • What roles do these classes play?
  • In what way the elements of the pattern are 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. The Builder pattern can be recognized in a class that has a single creation method and several methodsto configure the resulting object. The Builder interface specifies those methods for creating the different parts of a Product.
interface Builder
{
    public function producePartA(): void;
    public function producePartB(): void;
    public function producePartC(): void;
}
The RealBuilder classes follow the Builder interface and provides specific implementations of the building steps. The program may have several variations of Builders, implemented differently. We now build a class object called RealBuilder. The code for RealBuilder.php is as follows:
class RealBuilder implements Builder
{
    private $product;

    public function __construct()
    {
        $this->reset();
    }
    public function reset(): void
    {
        $this->product = new Product;
    }
    public function producePartA(): void
    {
        $this->product->parts[] = "PartA";
    }

    public function producePartB(): void
    {
        $this->product->parts[] = "PartB";
    }

    public function producePartC(): void
    {
        $this->product->parts[] = "PartC";
    }

    public function getProduct(): Product
    {
        $result = $this->product;
        $this->reset();

        return $result;
    }
}

Concrete Builders are supposed to provide their own methods for retrieving results. That's because various types of builders may create entirely different products that don't follow the same interface. Therefore, such methods cannot be declared in the base Builder interface (at least in a statically typed programming language). Note that PHP is a dynamically typed language and this method can be in the base interface. However, we won't declare it there for the sake of clarity.
Usually, after returning the end result to the client, a builder instance is expected to be ready to start producing another product. That's why it's a usual practice to call the reset method at the end of the getProduct method body. However, this behavior is not mandatory, and you can make your builders wait for an explicit reset call from the client code before disposing of the previous result. 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'now create a class called Product.
class Product
{
    public $parts = [];

    public function listParts(): void
    {
        echo "Product parts: " . implode(', ', $this->parts) . "

"; } }
Next we create a Director class. That file looks like:
class Director
{
    private $builder;

    public function setBuilder(Builder $builder): void
    {
        $this->builder = $builder;
    }

    public function buildMinimalViableProduct(): void
    {
        $this->builder->producePartA();
    }

    public function buildFullFeaturedProduct(): void
    {
        $this->builder->producePartA();
        $this->builder->producePartB();
        $this->builder->producePartC();
    }
}
Finally we go to the index.php an add some client code. First we need to add some include files:
include_once ('Builder.php');
include_once('RealBuilder.php');;
include_once('Product.php');
include_once ('Director.php');
for the client code we have:
function clientCode(Director $director)
{
    $builder = new RealBuilder;
    $director->setBuilder($builder);

    echo "Standard basic product:
"; $director->buildMinimalViableProduct(); $builder->getProduct()->listParts(); echo "Standard full featured product:
"; $director->buildFullFeaturedProduct(); $builder->getProduct()->listParts(); echo "Custom product:
"; $builder->producePartA(); $builder->producePartC(); $builder->getProduct()->listParts(); }
Lastly we add some client code to test our code
$director = new Director;
clientCode($director);
echo "end
";
The result we get is
Standard basic product:
Product parts: PartA

Standard full featured product:
Product parts: PartA, PartB, PartC

Custom product:
Product parts: PartA, PartC

end
Get the code!!
Wikipedia

Find Ray on:
facebook
youtube
The Ray Code
Ray Andrade

Thursday, March 25, 2021

Builder Design Pattern

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: * What classes does it consist of? * What roles do these classes play? * In what way the elements of the pattern are 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 is:
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 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 follow 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 Director. The code for our Director 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 demonsyration. 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

Wikipedia

Find Ray on:
facebook
youtube
The Ray Code
Ray Andrade

Wednesday, March 24, 2021

Abstract Factory Design Pattern using c#

In this article we will review the Abstract Factory pattern. This pattern allows you to create a family of classes in which the subclasses of this family can cooperate together. Let's start by creating a couple of interfaces we call IProductA and IProductB. We start with IProductA:
public interface IProductA
{
  string UsefulFunctionA();
}
We see that it requiers a UsefulFunctionA method to use it. Let's contine with the ProductA side. We add two real clases to use the interface. The code for the class ProductA1 is:
class ProductA1: IProductA
{
   public string UsefulFunctionA()
   {
      return "The result of the product A1.";
   }
}
and we will add another class we call **ProductA2** and its code will be:
class ProductA2: IProductA
{
   public string UsefulFunctionA()
   {
      return "The result of the product A2.";
    }
}
Now we do the same for another class we would like to add. We create a side for the other interphace we mention IProductB. We will add two clases also. Let's look at the code for the interface:
public interface IProductB
    {
        string UsefulFunctionB();
        string AnotherUsefulFunctionB(IProductA collaborator);

    }
As you can see there are 2 methods are required to use this interface. Let's create our first B class. We create ProductB1. The code for ProductB1 is:
class ProductB1: IProductB
{
    public string UsefulFunctionB()
    {
       return "The result of the product B1.";
    }
    public string AnotherUsefulFunctionB(IProductA collaborator)
    {
       var result = collaborator.UsefulFunctionA();
       return $"The result of the B1 collaborating with the ({result})";
    }
}
As you can see it fills the requirements of the interface IProductB. We create another class with the same requirements we call it ProductB2 Thee code for class ProductB2 will be:
class ProductB2: IProductB
{
   public string UsefulFunctionB()
   {
      return "The result of the product B2.";
   }
   public string AnotherUsefulFunctionB(IProductA collaborator)
   {
      var result = collaborator.UsefulFunctionA();
      return $"The result of the B2 collaborating with the ({result})";
   }
}
Now let's create the factory. We start with IAbstractFactory interface.
public interface IAbstractFactory
{
   IProductA CreateProductA();
   IProductB CreateProductB();
}
IProductA and IProductB are interfaces requiring a "UsefulFunction" We now create a couple Factories we call Factory1 and Factory2. We start with Factory1. The code for Factory1 is:
class Factory1: IAbstractFactory
{
   public IProductA CreateProductA()
   {
      return new ProductA1();
   }

   public IProductB CreateProductB()
   {
       return new ProductB1();
   }
}
Likewise for Factory2 we have:
class Factory2: IAbstractFactory
{
   public IProductA CreateProductA()
   {
      return new ProductA2();
   }

   public IProductB CreateProductB()
   {
      return new ProductB2();
   }
}
Finally we go to the Program.cs and add our Main method:
public static class Program
{
   public static void Main(string[] args)
   {
       new Client().Main();
   }
} 
When we compile and run we should get:
Client: Testing client code with the first factory type...
The result of the product B1.
The result of the B1 collaborating with the (The result of the product A1.)

Client: Testing the same client code with the second factory type...
The result of the product B2.
The result of the B2 collaborating with the (The result of the product A2.)

Wikipedia
Find Ray on:
facebook
youtube
The Ray Code
Ray Andrade

Tuesday, March 23, 2021

Abstract Factory Design Pattern using c++

In this article we will review the Abstract Factory pattern. This pattern allows you to create a family of classes in which the subclasses of this family can cooperate together. Let's start by creating a couple of products we call ProductA and ProductB. We start with ProductA and it's subclasses. For ProductA we have the following code:
class ProductA {
public:
    virtual ~ProductA(){};
    virtual std::string UsefulFunctionA() const = 0;
};
Next we want to create a couple subclasses that we call ProductA1 and ProductA2. The first thing we need to do is include ProductA.h and the extend ProductA1 with ProductA. Let's look at the code in ProductA1.h.
#include "ProductA.h"

class ProductA1 : public ProductA {
public:
    std::string UsefulFunctionA() const override {
        return "The result of the product A1.";
    }
};
We now want to create two classes I will call ProductA2 and ProductA2. Both classes will be extend with ProductA and thus we will need to include ProductA on both. The code for ProductA1 will be:
#include "ProductA.h"

class ProductA1 : public ProductA {
public:
    std::string UsefulFunctionA() const override {
        return "The result of the product A1.";
    }
};
and for ProductA2 we have:
#include "ProductA.h"

class ProductA2 : public ProductA {
    std::string UsefulFunctionA() const override {
        return "The result of the product A2.";
    }
};
Factory
We now move to the B side. So let's create ProductB. To ProductB we have the following code:
class ProductB {

public:
    virtual ~ProductB(){};
    virtual std::string UsefulFunctionB() const = 0;

    virtual std::string AnotherUsefulFunctionB(const ProductA &collaborator) const = 0;
};
Let's now create two classes that will be extended by this class. We first have ProductB1 and then we have ProductB2. Both will be extended with ProductB We start with ProductB1:
#include "ProductB.h"

class ProductB1 : public ProductB {
public:
    std::string UsefulFunctionB() const override {
        return "The result of the product B1.";
    }
    std::string AnotherUsefulFunctionB(const ProductA &collaborator) const override {
        const std::string result = collaborator.UsefulFunctionA();
        return "The result of the B1 collaborating with ( " + result + " )";
    }
};
and then we move to ProductB2. Its code will be:
#include "ProductB.h"

class ProductB2 : public ProductB {
public:
    std::string UsefulFunctionB() const override {
        return "The result of the product B2.";
    }

    std::string AnotherUsefulFunctionB(const ProductA &collaborator) const override {
        const std::string result = collaborator.UsefulFunctionA();
        return "The result of the B2 collaborating with ( " + result + " )";
    }
};
now let's create the AbstractFactory which will house our two classes ProductA and ProductB It will have the following code:
class AbstractFactory {
public:
    virtual ProductA *CreateProductA() const = 0;
    virtual ProductB *CreateProductB() const = 0;
};
Now let's create out Factories. We start with Factory1. We notice it is extended by the AbstractFactory. We have the following code:
#include "AbstractFactory.h"

class Factory1 : public AbstractFactory {
public:
    ProductA *CreateProductA() const override {
        return new ProductA1();
    }
    ProductB *CreateProductB() const override {
        return new ProductB1();
    }
};
We now proceed to Factory2. It too is extend by AbstractFactory thus we have the following code:
#include "AbstractFactory.h"

class Factory2 : public AbstractFactory {
public:
    ProductA *CreateProductA() const override {
        return new ProductA2();
    }
    ProductB *CreateProductB() const override {
        return new ProductB2();
    }
};
Our last step is to go to the main.cpp. First we add the includes that we need.
#include iostream >

#include "ProductA1.h"
#include "ProductA2.h"

#include "ProductB1.h"
#include "ProductB2.h"

#include "Factory1.h"
#include "Factory2.h"
we next add some client code:
void ClientCode(const AbstractFactory &factory) {
    const ProductA *product_a = factory.CreateProductA();
    const ProductB *product_b = factory.CreateProductB();
    std::cout << product_b->UsefulFunctionB() << "\n";
    std::cout << product_b->AnotherUsefulFunctionB(*product_a) << "\n";
    delete product_a;
    delete product_b;
}
our last step is to go to the main fundtion. This is the code that we need:
int main() {
    std::cout << "Client: Testing client code with the first factory type:\n";
    Factory1 *f1 = new Factory1();
    ClientCode(*f1);
    delete f1;
    std::cout << std::endl;
    std::cout << "Client: Testing the same client code with the second factory type:\n";
    Factory2 *f2 = new Factory2();
    ClientCode(*f2);
    delete f2;
    return 0;
}
We should be ready to compile this project and when we run it ou result should be: Client: Testing client code with the first factory type: The result of the product B1. The result of the B1 collaborating with ( The result of the product A1. ) Client: Testing the same client code with the second factory type: The result of the product B2. The result of the B2 collaborating with ( The result of the product A2. ) In this article we will review the Abstract Factory pattern using Php. This pattern allows you to create a family of classes in which the subclasses of this family can cooperate together. We start our demonstration by creating an interface we called AbstractFactory. The AbstractFactory interface declares a set of methods that return different abstract products. These products are called a family and are related by a high-level theme or concept. Products of one family are usually able to collaborate among themselves. A family of products may have several variants, but the products of one variant may be incompatible with the other products. Here is the code for this interface:

wiki/Abstract_factory_pattern
Be good and happy programming
Find Ray on:
facebook.com/TheRayCode/
youTube
The Ray Code
Ray Andrade

Monday, March 22, 2021

Abstract Factory Design Pattern using Php

In this article we will review the Abstract Factory pattern using Php. This pattern allows you to create a family of classes in which the subclasses of this family can cooperate together. We start our demonstration by creating an interface we called AbstractFactory. The AbstractFactory interface declares a set of methods that return different abstract products. These products are called a family and are related by a high-level theme or concept. Products of one family are usually able to collaborate among themselves. A family of products may have several variants, but the products of one variant may be incompatible with the other products. Here is the code for this interface:
interface AbstractFactory
{
    public function createProductA(): IProductA;

    public function createProductB(): IProductB;
}
As you can see we need a coulpe of classes accourding to this interface. Instead we will create and add a couple of interfaces for our project. The interfaces we want will be named IProductA and IProductB. We will start with the interface IProductA. The code for this file will be:
interface IProductA
{
    public function usefulFunctionA(): string;
}
We create another interface IProductB and we have:
interface IProductB
{
    public function usefulFunctionB(): string;

    public function anotherUsefulFunctionB(IProductA $collaborator): string;
}
The Abstract Factory makes sure that all products it creates are of the same type (*variant*) and thus are compatible. Let's now create our products. Our Concrete Products are created by corresponding their Concrete Factories. We will call them ProductA1, ProductA2, ProductB1 and ProductB2. We start with ProductA1.
class ProductA1 implements IProductA
{
    public function usefulFunctionA(): string
    {
        return "The result of the product A1.";
    }
}

Next for ProductA2 we have:
class ProductA2 implements IProductA
{
    public function usefulFunctionA(): string
    {
        return "The result of the product A2.";
    }
}
Both ProductA1 and ProductA2 implement IProductA. We now go to the IProductB side of our demonstration. The name of the classes will be ProductB1 and ProductB2. Both will implement IProductB. The variant, ProductB1, is only able to work correctly with the variant, ProductA1. Nevertheless, it accepts any instance of IProductA as argument. The code for ProductB1 is:
class ProductB1 implements IProductB
{
    public function usefulFunctionB(): string
    {
        return "The result of the product B1.";
    }
    
    public function anotherUsefulFunctionB(IProductA $collaborator): string
    {
        $result = $collaborator->usefulFunctionA();
        return "The result of the B1 collaborating with the ({$result})";
    }
}
The variant, ProductB2, is only able to work correctly with the variant, ProductA2. Nevertheless, it accepts any instance of IProductA as an argument. The code for ProductB2 will be:
class ProductB2 implements IProductB
{
    public function usefulFunctionB(): string
    {
        return "The result of the product B2.";
    }

    public function anotherUsefulFunctionB(IProductA $collaborator): string
    {
        $result = $collaborator->usefulFunctionA();

        return "The result of the B2 collaborating with the ({$result})";
    }
}
The Concrete Factories produce a family of products that belong to a single variant (type). The factory guarantees that resulting products are compatible. Note that signatures of the Concrete Factory's methods return an abstract product, while inside the method a concrete product is instantiated.
class Factory1 implements AbstractFactory
{
    public function createProductA(): IProductA
    {
        return new ProductA1;
    }

    public function createProductB(): IProductB
    {
        return new ProductB1;
    }
}
And for Factory2, it also implements the AbstractFactory
class Factory2 implements AbstractFactory
{
    public function createProductA(): IProductA
    {
        return new ProductA2;
    }
    public function createProductB(): IProductB
    {
        return new ProductB2;
    }
}
The last place we need to go is to the index.php file. The code for that file is:
function clientCode(AbstractFactory $factory)
{
  $productA = $factory->createProductA();
  $productB = $factory->createProductB();

  echo $productB->usefulFunctionB() . "
"; echo $productB->anotherUsefulFunctionB($productA) . "
"; } /** * The client code can work with any concrete factory class. */ echo "Client: Testing client code with the first factory type:
"; clientCode(new Factory1); echo "
"; echo "Client: Testing the same client code with the second factory type:
"; clientCode(new Factory2);
When we run the code we should get:
Client: Testing client code with the first factory type:
The result of the product B1.
The result of the B1 collaborating with the (The result of the product A1.)

Client: Testing the same client code with the second factory type:
The result of the product B2.
The result of the B2 collaborating with the (The result of the product A2.)
wiki/Abstract_factory_pattern
Be good and happy programming
Find Ray on:
facebook.com/TheRayCode/
youTube
The Ray Code
Ray Andrade

Saturday, March 20, 2021

Abstract Factory Design Pattern using Java

In this article we will review the Abstract Factory pattern. This pattern allows you to create a family of classes in which the subclasses of this family can cooperate together. The first thing I want to create is a package for our buttons. After doing that I create an interface called Button with the following code.
public interface Button {
  void paint();
}
This interface requires the paint method. The first button we add will be MacOSButton:
public class MacOSButton implements Button{
    @Override
    public void paint() {
        System.out.println("You have created MacOSButton.");
    }
}
Now let's add another button to our group. This time I will add a Windows button called WindowsButton. It's implementation look like:
public class WindowsButton implements Button {
    @Override
    public void paint() {
        System.out.println("You have created WindowsButton.");
    }
}
For the sake of the demo we will all another type of widget to our factory, we will add checkboxes. Let't first add a package for the checkboxes we call checkboxes. To this package we will add an interface for the checkboxes we all Checkbox. The code for this interface is just:
public interface Checkbox {
    void paint();
}
We create a couple of class objects to add to this package. The first one we create will be for the Mac OS naned MacOSCheckbox:
public class MacOSCheckbox implements Checkbox {
    @Override
    public void paint() {
        System.out.println("You have created MacOSCheckbox.");
    }
}
We create another class for Windows side WindowsCheckbox. The code for that is:
public class WindowsCheckbox implements Checkbox {
    @Override
    public void paint() {
        System.out.println("You have created WindowsCheckbox.");
    }
}
Now let's create a factory to harness both these button and checkbox classes. So we create a interface called GUIFactory. The code for that will be:
public interface GUIFactory {
    Button createButton();
    Checkbox createCheckbox();
}
For the MacOSFactory we have:
public class MacOSFactory implements GUIFactory {
    @Override
    public Button createButton() {
        return new MacOSButton();
    }

    @Override
    public Checkbox createCheckbox() {
        return new MacOSCheckbox();
    }
}
For the WindowsFactory we have.
public class WindowsFactory implements GUIFactory {
    @Override
    public Button createButton() {
        return new WindowsButton();
    }

    @Override
    public Checkbox createCheckbox() {
        return new WindowsCheckbox();
    }
}
Create an app package and place in it a class called Application. The code for this class is:
public class Application {
    private Button button;
    private Checkbox checkbox;

    public Application(GUIFactory factory) {
        button = factory.createButton();
        checkbox = factory.createCheckbox();
    }

    public void paint() {
        button.paint();
        checkbox.paint();
    }
}
The last class will be called Demo. Application picks the factory type and creates it in run time (usually at initialization stage), depending on the configuration or environment variables. The code for this class will be:
public class Demo {
    private static Application configureApplication() {
        Application app;
        GUIFactory factory;
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.contains("mac")) {
            factory = new MacOSFactory();
            app = new Application(factory);
        } else {
            factory = new WindowsFactory();
            app = new Application(factory);
        }
        return app;
    }

    public static void main(String[] args) {
        Application app = configureApplication();
        app.paint();
    }
}
your result should be
You have created WindowsButton.
You have created WindowsCheckbox.
[Wikipedia](https://en.wikipedia.org/wiki/Abstract_factory_pattern) wiki/Abstract_factory_pattern
Be good and happy programming
Find Ray on:
facebook.com/TheRayCode/
youTube
The Ray Code
Ray Andrade

Friday, March 19, 2021

Factory Design Pattern using Java

We start this demonstation with the goal to make two differnt systems render a button. One system will render simple html text and the other system we create will be for a *java*.awt and *javax*.swing systems. (We call this system a 'windows' system). We start off by creating the Java namespaces we need for this project. We create a package called buttons and another one called factory In the buttons package we create an interface we call Button. Here is the code for the interface:
public interface Button {
    void render();
    void onClick();
}
As you can see, the requirements to use this interface is to include the two methods render and onClick The first button we create will be for Html buttons. The name of this class will be HtmlButton. HtmlButton needs to implement Button. Because it is implementing Button we need to include a render method and an onClick our code looks like:
public class HtmlButton implements Button {

    public void render() {
        System.out.println("");
        onClick();
    }

    public void onClick() {
        System.out.println("Click! Button says - 'Hello World!'");
    }
}
So now let's create the same method using the awt/swing libraries. The code for this version will be:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
 * Windows button implementation.
 */
public class WindowsButton implements Button {
    JPanel panel = new JPanel();
    JFrame frame = new JFrame();
    JButton button;

    public void render() {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLabel label = new JLabel("Hello World!");
        label.setOpaque(true);
        label.setBackground(new Color(235, 233, 126));
        label.setFont(new Font("Dialog", Font.BOLD, 44));
        label.setHorizontalAlignment(SwingConstants.CENTER);
        panel.setLayout(new FlowLayout(FlowLayout.CENTER));
        frame.getContentPane().add(panel);
        panel.add(label);
        onClick();
        panel.add(button);

        frame.setSize(320, 200);
        frame.setVisible(true);
        onClick();
    }

    public void onClick() {
        button = new JButton("Exit");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                frame.setVisible(false);
                System.exit(0);
            }
        });
    }
}
Now let's turn to the factory side of our project. In the factory package we should have some core business that should group together. We create an abstract class we call Dialog this will be our code:
public abstract class Dialog {

    public void renderWindow() {
        Button okButton = createButton();
        okButton.render();
    }

    /**
     * Subclasses will override this method in order to create specific button
     * objects.
     */
    public abstract Button createButton();
}
We now define how our styles run. For the HTML side I write the following:
public class HtmlDialog extends Dialog {

   @Override
   public Button createButton() {
      return new HtmlButton();
   }
}
And for our window side we write:
public class WindowsDialog extends Dialog {

   @Override
   public Button createButton() {
      return new WindowsButton();
   }
}

Now let's put this all together in our Demo.java program. This is the code:
public class Demo {
    private static Dialog dialog;

    public static void main(String[] args) {
        configure();
        runBusinessLogic();
    }

    /**
     * The concrete factory is usually chosen depending on configuration or
     * environment options.
     */


    static void configure() {
    // use 1 or 2 to run

        switch(2) {
            case 1:
                dialog = new WindowsDialog();
                break;
            case 2:
                dialog = new HtmlDialog();
                break;
            default:
                // exit code block
        }
    }

    /**
     * All of the client code should work with factories and products through
     * abstract interfaces. This way it does not care which factory it works
     * with and what kind of product it returns.
     */
    static void runBusinessLogic() {
        dialog.renderWindow();
    }
}
Be good and happy programming
Find Ray on:
facebook.com/TheRayCode/
youTube
The Ray Code
Ray Andrade

Thursday, March 18, 2021

Factory Design Pattern using c#

For our example of the Factory pattern we will create an interface we call Product.cs. This interface will require one method. The code for Product looks like the following:
public interface Product
{
   string Operation();
}
Next we will create a couple of concrete products to add them to our project. The name of these products will be Product1 and Product2. The code for Product1 will be:
class Product1 : Product
{
   public string Operation()
   {
      return "{From of Product1}";
   }
}
And for the concrete product Product2 we have:
class Product2 : Product
{
   public string Operation()
   {
     return "{From of Product2}";
   }
}
Now let's focus on the abstract class we call Creator. It look's like:
abstract class Creator
{
   public abstract Product FactoryMethod();
   public string SomeOperation()
   {
      var product = FactoryMethod();
      var result = "Creator: This creator's code has just worked with "
                  + product.Operation();
      return result;
   }
}
Notice that the Creator also provides some default implementation of the factory method. Also note that, despite its name, the Creator's primary responsibility is not creating products. Usually, it contains some core business logic that relies on Product objects, returned by the factory method. Subclasses can indirectly change that business logic by overriding the factory method and returning a different type of product from it. Subclasses can indirectly change the business logic by overriding the factory and returning a different type. We add an abstract Product we call FactoryMethod. We then add SomeOperation to the progect class. We now create a couple of abstract class. Let's create these classes Creator1 and Creator2. We start with Creator1. This class returns a new Product1. Let's look at the code:
class Creator1 : Creator
{
   public override Product FactoryMethod()
   {
      return new Product1();
   }
}
likewise, the code for Creator2 will be like:
class Creator2 : Creator
{
   public override Product FactoryMethod()
   {
      return new Product2();
   }
}
Let's create a Director class that will run the Builder class object. The code for this class will be:
 public class Director
 {
    private Builder _builder;
    
    public Builder Builder
    {
       set { _builder = value; } 
    }
       
    // The Director can construct several product variations using the same
    // building steps.
    public void buildMinimalViableProduct()
    {
       this._builder.BuildPartA();
    }
        
    public void buildFullFeaturedProduct()
    {
      this._builder.BuildPartA();
      this._builder.BuildPartB();
      this._builder.BuildPartC();
    }
 }
Now let's put this all together in the Client.cs class.
class Client
{
    public void Main()
    {
        Console.WriteLine("App: Launched with the Creator1.");
        ClientCode(new Creator1());
           
        Console.WriteLine("");
        Console.WriteLine("App: Launched with the Creator2.");
        ClientCode(new Creator2());
    }
    public void ClientCode(Creator creator)
    {
        // ...
        Console.WriteLine("Client: I'm not aware of the creator's class," +
                          "but it still works.\n" + creator.SomeOperation());
        // ...
    }
}
and now let's run our work in the Program.cs class. We create the following code:
class Program
{
    static void Main(string[] args)
    {
        new Client().Main();
    }
}
We are ready to run our program and thus we have:
App: Launched with the Creator1.
Client: I'm not aware of the creator's class,but it still works.
Creator: This creator's code has just worked with {From of Product1}

App: Launched with the Creator2.
Client: I'm not aware of the creator's class,but it still works.
Creator: This creator's code has just worked with {From of Product2}
Be good and happy programming
[image]
Find Ray on:
facebook.com/TheRayCode/
youTube
The Ray Code
Ray Andrade

Wednesday, March 17, 2021

Factory method design pattern using c++

Creational Pattern

In this artical I will take a look at the Factory design pattern using c++. We start by creating an interface we call Product.
#include 

class Product {
public:
    virtual ~Product() {}
    virtual std::string Operation() const = 0;
};

This interface accepts two methods. A destructor for Product and a method we generically call Operation.
**Operation** returns a string.

Now we will create two concrete product clases one called ProductA and the other **ProductB**. 
Concrete Products provide various implementations of the Product interface.
The code for ProductA  is:
#include "Product.h"

class ProductA : public Product {
public:
    std::string Operation() const override {
        return "{Result of ProductA}";
    }
};
For ProductB the code is:
 
#include "Product.h"

class CProductB : public Product {
public:
    std::string Operation() const override {
        return "{Result of ProductB}";
    }
};
The next interface we create is Creator. Note that the Creator may also provide some default implementation of the factory method.

The Creator class declares the factory method that is supposed to return an
 * object of a Product class. The Creator's subclasses usually provide the
 * implementation of this method

The code for is:
#include "Creator.h"
#include "ProductA.h"

class CreatorA : public Creator {

public:
    Product* FactoryMethod() const override {
        return new ProductA();
    }
};
We include both Creator.h and ProductB.h. 
We also extend the class with Creator.

We do the same for another class we create CreatorB.h and extend it also with Creator class.
In the FactoryMethod we return a new ProductB
#include "Creator.h"
#include "ProductB.h"

class CreatorB : public Creator {

public:
    Product* FactoryMethod() const override {
        return new ProductB();
    }
};
Lastly we go to main.cpp. First we add the includes that we will be using:
#include "Product.h"
#include "ProductA.h"
#include "ProductB.h"
#include "Creator.h"
#include "CreatorA.h"
#include "CreatorB.h"
The client code works with an instance of a concrete creator, albeit through * its base interface. As long as the client keeps working with the creator via * the base interface, you can pass it any creator's subclass.
void ClientCode(const Creator & creator) {
    // ...
    std::cout << "Client: I'm not aware of the creator's class, but it still works.\n"
              << creator.SomeOperation() << std::endl;
    // .
}
Our last bit of code we add will be our **main** method:
int main() {

    std::cout << "App: Launched with the CreatorA." << std::endl;
    Creator* creatorA = new CreatorA();
    ClientCode(*creatorA);

    std::cout << std::endl;
    std::cout << "App: Launched with the CreatorB." << std::endl;
    Creator* creatorB = new CreatorB();
    ClientCode(*creatorB);

    delete creatorA;
    delete creatorB;

    std::cout << "The Ray Code is AWESOME!!!" << std::endl;
    return 0;
}

The result shoud be:
App: Launched with the CreatorA.
Client: I'm not aware of the creator's class, but it still works.
Creator: The same creator's code has just worked with {Result of the ProductA}

App: Launched with the CreatorB.
Client: I'm not aware of the creator's class, but it still works.
Creator: The same creator's code has just worked with {Result of the ProductB}

wikipedia.org github.com ---------------------------------------------------------------------------------------------------- Find Ray on: facebook.com/TheRayCode/ youtube.com/user/AndradeRay/ The Ray Code Ray Andrade

Tuesday, March 16, 2021

Factory method design pattern using PHP

Creational Pattern

Factory methods can be recognized by creation methods, which create objects from concrete classes, but return them as objects of abstract type or interface. In this post we will explore the Factory method using PHP. We will start by creating an interface for our products. Let's call this interface Product.php. Product.php will require one Operation for its use. The Product interface declares the operations that all concrete products must implement. Let's take a look at the code:
interface Product
{
   public function operation(): string;
}
We will also create a couple of Products to use this interface. Products provide various implementations of the Product interface.
class Product1 implements Product
{
   public function operation(): string
   {
      return "{Result of the Product1}";
   }
}

Likewise we create another Prodect we call Product2.php

class Product2 implements Product
{
   public function operation(): string
   {
      return "{Result of the Product2}";
   }
}
The Creator class declares the factory method that is supposed to return an object of a Product class. The Creator's subclasses usually provide the implementation of this method.
Let's create an abstract class we call Creator.php.
Inside this abstract class we have a couple of puplic functions:
abstract class Creator
{
    abstract public function factoryMethod(): Product;

    public function someOperation(): string
    {
        $product = $this->factoryMethod();
        $result = "Creator: The same creator's code has just worked with " .
            $product->operation();
        return $result;
    }
}

Note that the Creator may also provide some default implementation of the factory method.

Also note that, despite its name, the Creator's primary responsibility is not creating products. 
Usually, it contains some core business logic that relies on Product objects, returned by the factory method. 
Subclasses can indirectly change that business logic by overriding the factory method  and returning a different type of product from it.

Concrete Creators override the factory method in order to change the resulting product's type.

class Creator1 extends Creator
{
   public function factoryMethod(): Product
   {
      return new Product1();
   }
}

Note that the signature of the method still uses the abstract product type, even though the concrete product is actually returned from the method. 
This way the Creator can stay independent of concrete product classes.

Let's add another Creator class to our project.

class Creator2 extends Creator
{
   public function factoryMethod(): Product
   {
      return new Product2();
   }
}
We are now ready to put this all together in the index.php for our demonstration.

We make sure we have all the includes:
 
include_once ('Creator.php');
include_once('Creator1.php');
include_once('Creator2.php');
include_once ('Product.php');
include_once('Product1.php');
include_once('Product2.php');
 
next we create some client code for our demo

function clientCode(Creator $creator)
{
   echo Client: "I'm not aware of the creator's class, 
                but it still works". < br/ >
        . $creator->someOperation();
}

The Application picks a creator's type depending on the configuration or environment.


echo "App: Launched with the Creator1. < br/ >
clientCode(new Creator1);
echo < br/ > < br/ > 

echo "App: Launched with the Creator2. < br/ >";
clientCode(new Creator2);

When we veiw our result through a browser we have:

App: Launched with the Creator1.
Client: I'm not aware of the creator's class, but it still works.
Creator: The same creator's code has just worked with {Result of the Product1}

App: Launched with the Creator2.
Client: I'm not aware of the creator's class, but it still works.
Creator: The same creator's code has just worked with {Result of the Product2}

wiki/Factory_method_pattern
----------------------------------------------------------------------------------------------------
Find Ray on:
facebook.com/TheRayCode
youtube.com/user/AndradeRay/
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...