Tuesday, March 31, 2020

Proxy Design Pattern




The next design pattern that is going to be covered in this blog series is Proxy Design pattern.
As per the name suggests, Proxy means a figure that can be used to represent the value of something in calculation or ‘representing’ in the context of the design pattern that we are discussing here. These are also named as surrogates, handles and wrappers.
Real world example- A credit card is a proxy for a bank account, which is a proxy for cash. No need to carry loads of money with you all the time and the money directly being sent shop’s bank account which results in win for both the parties. Instead of cash, you are using different means like credit card to represent the real money. The main purpose of proxy pattern is also the same – ‘To represent and control the access to the object that is under their protection.’

When do we use this designing pattern? – When you intend to cover the main object’s complexity from the client.
Code to display basic implementation of proxy design pattern.

#include <iostream>
using namespace std;
class ProxyBase {
public:
virtual void f() = 0;
virtual void g() = 0;
virtual void h() = 0;
virtual ~ProxyBase() {}
};
class Implementation : public ProxyBase {
public:
void f() { cout << "Implementation.f()" << endl; }
void g() { cout << "Implementation.g()" << endl; }
void h() { cout << "Implementation.h()" << endl; }
};
class Proxy : public ProxyBase {
ProxyBase* implementation;
public:
Proxy() { implementation = new Implementation(); }
~Proxy() { delete implementation; }
// Forward calls to the implementation:
void f() { implementation->f(); }
void g() { implementation->g(); }
void h() { implementation->h(); }
};
int main() {
Proxy p;
p.f();
p.g();
p.h();
}
Output:
References:

Sunday, March 29, 2020

Adapter Design Pattern


As we discussed earlier there are lots of design pattern in OOPs. We discussed following design pattern:

Singleton design pattern
Abstract factory design pattern
Decorator design pattern
Flyweight design pattern
Observer design pattern

In this blog, we discuss Adapter design pattern is one of the structural design patterns which is used for to interface two unrelated work with each other.

We are all familiar with adapter, it is a device which is used to connect two incompatible devices to do some work. Adapter which can put into the power socket and then put your plug into another end of the adapter. The adapter changes the form of your plug so that can use it with the power socket. But adapter doesn’t provide any additional functionality. It just connects plug and power supply.
 
For example, in real time application, to read the memory card via laptop it is impossible without adapter. So, in this situation card reader is act as a adapter between laptop and memory card. If we plugin the memory card into the card reader and card reader into a laptop. Then memory card can be easily read via laptop.

In this design pattern, the work of adapter design pattern same like adapter device. Here adapter convert interface of one class into interface of another class that the client expects. Adapter design pattern is also known as the wrapper. 

There are two types of adapters:
  • Object Adapter 
  • Class Adapter

Object Adapter:
Object adapters use a compositional technique to adapt one interface to another inaterface. The adapter inherits the target interface that the client want to see. It hold an instance the adaptee (Target and adaptee is also called as legacy system which is pre-exist). When the client call the request method on its target object, the request is translated into the corresponding specific request on the adaptee. Object adapter provide that the client completely decoupled from the adaptee. Only adapter knows about both of them. Below block diagram shows the object adapter design pattern. 

Class Adapter:
Class adapter uses multiple inheritance and can only wrap a class. As in the object adapter, the class adapter inherits the interface of the adaptee as well. But java does not support multiple inheritance, this means that one of the interfaces must be inherited from a java interface type. The class adapter subclass the target and the adaptee. If client request to the target is simply rerouted to the specific request which is inherit from the adaptee interface. Fig below shows the block diagram of class adapter design pattern.


Code: 
#include <iostream>
using namespace std;
typedef int Coordinate;
typedef int Dimension;

// Desired interface (Target)
class Rectangle
{
  public:
    virtual void draw() = 0;
};

// Legacy component (Adaptee)
class LegacyRectangle
{
  public:
    LegacyRectangle(Coordinate x1, Coordinate y1, Coordinate x2, Coordinate y2)
    {
        x1_ = x1;
        y1_ = y1;
        x2_ = x2;
        y2_ = y2;
        cout << "LegacyRectangle:  create.  (" << x1_ << "," << y1_ << ") => ("
          << x2_ << "," << y2_ << ")" << endl;
    }
    void oldDraw()
    {
        cout << "LegacyRectangle:  oldDraw.  (" << x1_ << "," << y1_ <<
          ") => (" << x2_ << "," << y2_ << ")" << endl;
    }
  private:
    Coordinate x1_;
    Coordinate y1_;
    Coordinate x2_;
    Coordinate y2_;
};

// Adapter wrapper
class RectangleAdapter: public Rectangle, private LegacyRectangle
{
  public:
    RectangleAdapter(Coordinate x, Coordinate y, Dimension w, Dimension h):
      LegacyRectangle(x, y, x + w, y + h)
    {
        cout << "RectangleAdapter: create.  (" << x << "," << y <<
          "), width = " << w << ", height = " << h << endl;
    }
    virtual void draw()
    {
        cout << "RectangleAdapter: draw." << endl;
        oldDraw();
    }
};

int main()
{
  Rectangle *r = new RectangleAdapter(120, 200, 60, 40);   //Request for target
  r->draw();
}

Result:



Explanation:
  •  In main() client class the Rectangle class. So, here Rectangle is a target.
  • As adapter design pattern, inherit multiple classes. Here class RectangleAdapter inherits the Rectangle(base) and LegacyRectangle(Adaptee).
  • The Adapter RectangleAdapter lets the LegacyRectangle responds to request(draw() on a Rectangle)by inheriting both classes.
  • The LegacyRectangle class does not have the same methods(draw())as Rectangle, but the Adapter (RectangleAdapter)can takes the Rectangle method calls and invoke method on the LegacyRectangle, oldDraw(). 




Video Link of Blog: https://drive.google.com/a/vit.edu/file/d/104WSJuztOzL-4ZASIsFXIO8BHP9tK3Py/view?usp=drivesdk









Saturday, March 14, 2020

Observer Design Pattern

-What is Observer Design Pattern?

     When multiple objects aka observers are dependancies of a subject class, and it's elements, the Observer Design Pattern comes in action. So, how does it work? When an element of the subject class changes, all it's dependant objects are notified, and updated automatically with the changes occured.

    Let's take an example. Consider an IPL auction going on. The auctioneer starts a bid on a player, say Sunil Narayan, who is the subject in this case. It has 1 property as price which is a dependancy in all the observer objects; teams here. Whenever a bidder i.e. an observer raises the bid price, the final price get's updated and notified to all other bidders automatically in real time, and new bid is added to the updated price. Similarly, the observer design pattern works in such manner.

     Another example of ongoing T-20 cricket match, observer design pattern is used:

#include<iostream>

class Runrate {public:
    float run_rate, over;
    int predicted;

    void update(int run, int wicket, float over) {
        if(over == 0)
            std::cout<<'\n';
        else {
            this->over = over;
            over = (int)over + ((float)over - (int)over)*1.667;
//            std::cout<<over<<'\n';
            run_rate = (float)run/over;
            predicted = (float)run_rate*20;
   
        }
    }

};

class Disp_score {

    int run, wicket;
    float over;

    public:
    void display(int run, int wicket, float over, float run_rate, int predicted) {

        std::cout<<run<<"/"<<wicket<<"\t"<<over<<"\tRunrate:"<<run_rate<<"\nPredicted score"<<predicted<<'\n';
    }

};
class Cricket {public:

    int run, wicket;
    float over;
    Runrate rate;
    Disp_score dis;

    Cricket(int runs, int wis, float overs, float rrate, int pred){
       
        rate.update(runs, wis, overs);
        dis.display(runs, wis, overs, rrate, pred);
    }

    void notify(int run, int wis, float over){

        rate.update(run, wis, over);
        dis.display(run, wis, over, rate.run_rate, rate.predicted);
    }

    void set_data(int runs, int wis, float overs){
        run = runs;
        wicket = wis;
        over = overs;
        notify(run, wicket, over);

    }
};

int main(){

    Cricket s(0,0,0.0, 0.0, 0);
    int r, w;
    float o;

    while(1){
       
        std::cout<<"Update:\nRuns wickets overs";
        std::cin>>r>>w>>o;
        s.set_data(r, w , o);
    }
    return 0;
}

   Consider a class 'Cricket' as a subject, which contain few members on which two Observer classes; Run_rate and Disp_score which are depend on the  members of the subject class. Run_rate observer needs members run and overs to calculate the run rate and predicted score. And observer Disp_score needs members runs, wickets, and overs from Cricket class, and run_rate and predicted of Runrate class.
   Here, class Cricket has 2 observers Runrate and Disp, and Disp class is observer of both Runrate class as well as Cricket class.



 

References: https://sourcemaking.com/design_patterns/observer/cpp/1
https://www.geeksforgeeks.org/observer-pattern-set-1-introduction/








Tuesday, March 3, 2020

Flyweight Design Pattern

 What is the Flyweight design pattern and why we use ?

 The topic is Flyweight design pattern in programming language flyweight is a software design pattern. A flyweight is an object that minimizes memory usage by sharing as much data as possible with other similar object.
               it is way to use objects in large numbers when simple Repeated representation would use an unacceptable amount of memory.  therefore it is devided into two parts shown in  flyweight design pattern class diagram . if multiple objects have some part is comman means feature or any internal part is same then this object share these memory with the help of that we can reduced memory consumption. and the same part of different objects is stored and shared via a Flyweight object.
The common part of various object is stored and shared via a “Flyweight” object.

Flyweight Factory : it is a factory class which is used by client class to get data from the concrete_flyweight . this class is also responsible for creating a pool of already created objects.so when a request comes from data that is already requested, it returns data from pool.



 Flyweight Design Pattern Example :  

 In this example we take a Aeroplane industry model means each Aeroplane information is stored in the form of class objects. so each have same entity like type of aircraft , seating capacity,speed etc.
these information stored in two different ways because some entities are same and other is unique.
     so same information can be stored at one place in flyweight objects which will be shared by all same kind of objects. and other information like every aircraft will have serial number and manufacturing date information which are unique per aircraft that's why ,these information will be saved directly in final object.

Code:
     
   #include<iostream>
  using namespace std;
 class Product
{
    private:
    string p_name;
    int p_capacity;
    int p_speed;

   public:
    virtual void showDetails()
    {
        cout<<"Name : "<<p_name<<", Capacity : "<<p_capacity<<", Speed: "<<p_speed<<" knots"  <<endl;
    }
    Product(string name, int capacity, int speed)
    {
        p_name = name;
        p_capacity = capacity;
        p_speed = speed;
    }
    Product(){};
};

/* Flyweight Concrete Class */
class Boeing380: public Product
{
 public:
    Boeing380():Product("Boeing380", 200, 800) {}
};

/* Flyweight Concrete Class */
class Airbus787: public Product
{
 public:
    Airbus787():Product("Airbus787", 600, 1000) {}
};

/* Flyweight Concrete Class */
class Airbus797: public Product
{
public:
    Airbus797():Product("Airbus797", 1200, 1500) {}
};
/* Flyweight Factory Class */
class FlyweightFact
{
private:
    static Boeing380* s_boeing380;
    static Airbus787* s_airbus787;
    static Airbus797* s_airbus797;

public:
    static Product* getProduct(int type)
    {
        switch(type)
        {
        case 380:
            if(!s_boeing380)
            {
                s_boeing380 = new Boeing380();
            }
            return s_boeing380;

        case 787:
            if(!s_airbus787)
            {
                s_airbus787 = new Airbus787();
            }
            return s_airbus787;
            
        case 797:
            if(!s_airbus797)
            {
                s_airbus797 = new Airbus797();
            }
            return s_airbus797;

        default:
            cout<<"Unknown aeroplane type"<<endl;
            return NULL;
        }
    }
};

Boeing380* FlyweightFact::s_boeing380;
Airbus787* FlyweightFact::s_airbus787;
Airbus797* FlyweightFact::s_airbus797;
/* Product Class */
class Aeroplane: public Product
{
private:
    Product* p_product;
    string p_mfgDate;
    int p_id;

public:
    Aeroplane(Product* product, string date, int id)
    {
        p_product = product;
        p_mfgDate = date;
        p_id = id;
    }

    virtual void showDetails()
    {
        p_product->showDetails();
        cout<<"MfgDate : "<<p_mfgDate<<", Serial No: "<<p_id<<endl;
    }
};

int main()
{
    Aeroplane first = Aeroplane(FlyweightFact::getProduct(787), "10th May 1997", 100213);
    Aeroplane second = Aeroplane(FlyweightFact::getProduct(797), "1st Aug 1998", 100214);
    Aeroplane third = Aeroplane(FlyweightFact::getProduct(787), "20th Aug 2000", 100215);
    Aeroplane forth = Aeroplane(FlyweightFact::getProduct(380), "10th Jan 2002", 200216);

    first.showDetails();
    second.showDetails();
    third.showDetails();
    forth.showDetails();
}



Output :























Course Project: 3 Lane Car Game

Course Project Title:  3 lane car racing game Course Project Description:              The aim of our course project is to implement...