Proxy Pattern

Proxy Pattern comes under Structural Pattern.

According to Gang Of Four Intent of Proxy Pattern is to Provide a surrogate or placeholder for another object to control access to it.

UML DIAGRAM:




SAMPLE CODE:

#include <iostream>

using namespace std;

class Vote {
public:
    virtual void castVote(string name, int age) = 0;
};

class VoteSystem : public Vote {
public:
    void castVote(string name, int age)
    {
        cout << "NAME : " << name << ", AGE : " << age << " Casted Vote Successfully" << endl;
    }
};

class IndianVoteSystem : public Vote { // Proxy class
    Vote* voteOper;

public:
    IndianVoteSystem()
    {
        voteOper = new VoteSystem();
    }

    void castVote(string name, int age)
    {
        if (age >= 18) { // if age is more than 18 cast vote
            voteOper->castVote(name, age);
        }
        else {
            cout << age << " Years is Not Eligible Age to Cast Vote in India" << endl;
        }
    }
};

int main()
{
    string name;
    int age;

    Vote* indiaPoll = new IndianVoteSystem();

    cout << "Name ? "; cin >> name;
    cout << "Age  ? "; cin >> age;

    indiaPoll->castVote(name, age);

    return 0;

}


OUTPUT:

Name ? hirthik
Age  ? 16
16 Years is Not Eligible Age to Cast Vote in India

Name ? sharma
Age  ? 34
NAME : sharma, AGE : 34 Casted Vote Successfully

Name ? rahul
Age  ? 18
NAME : rahul, AGE : 18 Casted Vote Successfully

                                               INDEX - OTHER DESIGN PATTERNS

Bridge Pattern

Bridge Pattern is one of the Structural Design Pattern.

According to GoF intent of Bridge Pattern is to Decouple an abstraction from its implementation so that the two can vary independently.


SAMPLE CODE:

#include <iostream>

using namespace std;

class IColour {
public:
    virtual void paintColour() = 0;
};

class RedColour : public IColour {
public:
    void paintColour()
    {
        cout << "RED Colour Paint" << endl;
    }
};

class GreenColour : public IColour {
public:
    void paintColour()
    {
        cout << "GREEN Colour Paint" << endl;
    }
};

class IShape {
protected:
    IColour* colour;
public:
    IShape (IColour* colour) {
        this->colour = colour;
    }
    virtual void draw() = 0;
};

class Circle : public IShape {
public:
    Circle(IColour* c) : IShape(c) {
    }

    void draw()
    {
        cout << "Draw a Cirle With ";
        colour->paintColour();
    }
};

class Square : public IShape {
public:
    Square(IColour* c) : IShape(c) {
    }

    void draw()
    {
        cout << "Draw a Square With ";
        colour->paintColour();
    }
};

int main()
{
    RedColour redPaint;
    GreenColour greenPaint;
    IShape* circleImage, *squareImage;

    circleImage = new Circle(&redPaint);
    circleImage->draw();

    squareImage = new Square(&greenPaint);
    squareImage->draw();

    return 0;

}


OUTPUT:

Draw a Cirle With RED Colour Paint

Draw a Square With GREEN Colour Paint

                                               INDEX - OTHER DESIGN PATTERNS

Template Method Pattern

Template Method Pattern is one of the Behavioral design pattern.

According to Gang Of Four intent of Template Method Pattern is to Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.


SAMPLE CODE:

#include <iostream>

using namespace std;

class CoffeeTemplate {
private:
    virtual void boilWater()
    {
        cout << "  * Boiling Water" << endl;
    }
    virtual void addMilk()
    {
        cout << "  * Adding Milk" << endl;
    }
    void addSugar()
    {
        cout << "  * Adding Sugar" << endl;
    }

    virtual void addCoffee() = 0;

public:
    void makeCoffee() /* Template Method */
    {
        cout << "Start Making Coffee" << endl;
        boilWater();
        addMilk();
        addCoffee();
        addSugar();
        cout << "Tasty Coffee Ready Enjoy!!!" << endl << endl;
    }
};

class NescafeeCoffee : public CoffeeTemplate {
    void addCoffee()
    {
        cout << "  * Adding Nescafee Coffee Podwer" << endl;
    }
};

class BruCoffee : public CoffeeTemplate {
    void addCoffee()
    {
        cout << "  * Adding Bru Coffee Powder" << endl;
    }
};

class SunriseCoffee : public CoffeeTemplate {
    void addCoffee()
    {
        cout << "  * Adding Sunrise Coffee Powder" << endl;
    }
};

int main()
{
    CoffeeTemplate* coffee = new BruCoffee();
    coffee->makeCoffee();

    coffee = new SunriseCoffee();
    coffee->makeCoffee();
    return 0;
}

OUTPUT:

Start Making Coffee
  * Boiling Water
  * Adding Milk
  * Adding Bru Coffee Powder
  * Adding Sugar
Tasty Coffee Ready Enjoy!!!

Start Making Coffee
  * Boiling Water
  * Adding Milk
  * Adding Sunrise Coffee Powder
  * Adding Sugar
Tasty Coffee Ready Enjoy!!!

                                               INDEX - OTHER DESIGN PATTERNS



Observer Pattern

Intent of Observer Design Pattern is to Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Observer pattern comes under Behavioral Pattern.

SAMPLE CODE:

#include <iostream>
#include <vector>
#include <unistd.h>
#include <time.h>

using namespace std;

class Subject;

class Observer {
public:
    string name;
    virtual void update() = 0;
};

class Subject {
private:
        vector <Observer*> observers;

public:
    void attach(Observer* obser)
    {
        observers.push_back(obser);
        cout << obser->name << " Suscribed To Get Notification" << endl << endl;
    }

    void detach(Observer* obser)
    {
        int observerCount = observers.size();
        for (int i = 0; i < observerCount; i++) {
            if (observers[i] == obser) {
                observers.erase(observers.begin() + i);
                cout << obser->name << " Unsuscribed From Receiving Notification" << endl;
                break;
            }
        }
    }

    void notify()
    {
        time_t now = time(NULL);
        struct tm * curtime = localtime(&now);
        cout << asctime(curtime);

        int observerCount = observers.size();
        for (int i = 0; i < observerCount; i++) {
            observers[i]->update();
        }
    }

};

class OfferPage : public Subject {
private:
    string  productName;
    double  actualPrice;
    double  offerPrice;

public:
    void setOffer(string product, int actual, int offer)
    {
        productName = product;
        actualPrice = actual;
        offerPrice = offer;
    }

    string getProduct()
    {
        return productName;
    }

    int getActualPrice()
    {
        return actualPrice;
    }

    int getOfferPrice()
    {
        return offerPrice;
    }
};

class GmailUsers : public Observer {
private:
    OfferPage* offerOfDay;

public:
    GmailUsers(OfferPage* offer)
    {
        name = "Gmailusers";
        offerOfDay = offer;
    }

    void update()
    {
        string product = offerOfDay->getProduct();
        double actPrice = offerOfDay->getActualPrice();
        double offPrice = offerOfDay->getOfferPrice();
        cout << "----> Sent TO Gmail Users" << endl;
        cout << "  Offer Of The Day - " << product << endl;
        cout << "    Actual Price   - " << actPrice << " USD" << endl;
        cout << "    Offer Price    - " << offPrice << " USD" << endl;
        cout << "    Savings        - " << (actPrice - offPrice) << " USD" << endl ;
    }
};

class YahooUsers : public Observer {
private:
    OfferPage* offerOfDay;
    
public:
    YahooUsers(OfferPage* offer)
    {
        name = "YahooUsers";
        offerOfDay = offer;
    }

    void update()
    {
        string product = offerOfDay->getProduct();
        double actPrice = offerOfDay->getActualPrice();
        double offPrice = offerOfDay->getOfferPrice();
        cout << "----> Sent TO Yahoo Users" << endl;
        cout << "  Offer Of The Day - " << product << endl;
        cout << "    Actual Price   - " << actPrice << " USD" << endl;
        cout << "    Offer Price    - " << offPrice << " USD" << endl;
        cout << "    Savings        - " << (actPrice - offPrice) << " USD" << endl << endl;
    }
};

int main()
{
    OfferPage todayOffer;
    todayOffer.setOffer("IPHONE 5S", 740, 725);

    Observer* gmailSuscriber = new GmailUsers(&todayOffer);
    todayOffer.attach(gmailSuscriber);
    Observer* yahooSuscriber = new YahooUsers(&todayOffer);
    todayOffer.attach(yahooSuscriber);

    todayOffer.notify();

    sleep(5);
    todayOffer.setOffer("Dell Laptop", 850, 839);
    todayOffer.notify();

    return 0;
}


OUTPUT:

Gmailusers Suscribed To Get Notification

YahooUsers Suscribed To Get Notification

Sun Oct  4 14:00:13 2015
----> Sent TO Gmail Users
  Offer Of The Day - IPHONE 5S
    Actual Price   - 740 USD
    Offer Price    - 725 USD
    Savings        - 15 USD
----> Sent TO Yahoo Users
  Offer Of The Day - IPHONE 5S
    Actual Price   - 740 USD
    Offer Price    - 725 USD
    Savings        - 15 USD

Sun Oct  4 14:00:18 2015
----> Sent TO Gmail Users
  Offer Of The Day - Dell Laptop
    Actual Price   - 850 USD
    Offer Price    - 839 USD
    Savings        - 11 USD
----> Sent TO Yahoo Users
  Offer Of The Day - Dell Laptop
    Actual Price   - 850 USD
    Offer Price    - 839 USD
    Savings        - 11 USD


                                               INDEX - OTHER DESIGN PATTERNS

Facade Pattern

According to Gang Of Four intent of Facade Design pattern is to Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

SAMPLE CODE:

#include <iostream>

using namespace std;

class PreprocessorSystem {
public:
    void doPreprocess()
    {
        cout << "--->Program In Preprocessing Stage" << endl;
    }
};

class CompilerSystem {
public:
    void doCompile()
    {
        cout << "--->Program In Compile Stage" << endl;
    }
};

class AssemblerSystem {
public:
    void doAssembly()
    {
        cout << "--->Program in Assembling Stage" << endl;
    }
};

class LinkerSystem {
public:
    void doLinking()
    {
        cout << "--->Program In Linking Stage" << endl;
    }
};

class CompilerFacade {
private:
    PreprocessorSystem  preprocessor;
    CompilerSystem      compiler;
    AssemblerSystem     assembler;
    LinkerSystem        linker;

public:
    void Compile(string programName)
    {
        cout << programName << " Compliation Started" << endl;
        preprocessor.doPreprocess();
        compiler.doCompile();
        assembler.doAssembly();
        linker.doLinking();
        cout << programName << " Compilation Finished" << endl;
    }
};

int main()
{
    CompilerFacade clientCompiler;
    clientCompiler.Compile("MYPROGRAM.cpp");

    return 0;
}   


OUTPUT:

MYPROGRAM.cpp Compliation Started
--->Program In Preprocessing Stage
--->Program In Compile Stage
--->Program in Assembling Stage
--->Program In Linking Stage
MYPROGRAM.cpp Compilation Finished

                            INDEX - OTHER DESIGN PATTERNS

Abstract Factory Pattern

Abstract Factory Pattern is one of the creational design pattern.

According to Gang Of Four intent of Abstract Factory Pattern is to Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

SAMPLE CODE:

#include <iostream>

using namespace std;

enum DBType { MYSQL, ORACLE, REDIS, MANGODB };

class Database {
public:
    virtual void read() = 0;
    virtual void write() = 0;
};

class MysqlDB : public Database {
    void read() {
        cout << "Read data from MYSQL RDBMS Database" << endl;
    }
    void write() {
        cout << "Write data to MYSQL RDBMS Database" << endl;
    }
};

class OracleDB : public Database {
    void read() {
        cout << "Read data from ORACLE RDBMS Database" << endl;
    }
    void write() {
        cout << "Write data to ORACLE RDBMS Database" << endl;
    }
};

class RedisDB : public Database {
    void read() {
        cout << "Read data from REDIS NOSQL Database" << endl;
    }
    void write() {
        cout << "Write data to REDIS NOSQL Database" << endl;
    }
};

class MangoDB : public Database {
    void read() {
        cout << "Read data from MANGODB NOSQL Database" << endl;
    }
    void write() {
        cout << "Write data to MANGODB NOSQL Database" << endl;
    }
};

class DataBaseFactory {
public:
    virtual Database * getDatabase(DBType choice) = 0;
};

class RDBMSFactory : public DataBaseFactory {
    Database * getDatabase(DBType choice) {
        Database * DBObject;
        if (choice == MYSQL) {
            DBObject = new MysqlDB();
        }
        else if (choice == ORACLE) {
            DBObject = new OracleDB();
        }
        else {
            DBObject = NULL;
        }
        return DBObject;
    }
};

class NOSQLFactory : public DataBaseFactory {
    Database * getDatabase(DBType choice) {
        Database * DBObject;
        if (choice == REDIS) {
            DBObject = new RedisDB();
        }
        else if (choice == MANGODB) {
            DBObject = new MangoDB();
        }
        else {
            DBObject = NULL;
        }
        return DBObject;
    }
};

int main()
{
    DataBaseFactory * rdbmsObject, * nosqlObject;
    Database * databaseObject;

    rdbmsObject = new RDBMSFactory();
    databaseObject = rdbmsObject->getDatabase(ORACLE);
    databaseObject->read();
    databaseObject->write();
    cout << "-----------------------------------------" << endl;
    nosqlObject = new NOSQLFactory();
    databaseObject = nosqlObject->getDatabase(REDIS);
    databaseObject->read();
    databaseObject->write();

    return 0;
}


OUTPUT:

Read data from ORACLE RDBMS Database
Write data to ORACLE RDBMS Database
-----------------------------------------
Read data from REDIS NOSQL Database
Write data to REDIS NOSQL Database


Factory Method Pattern

Factory Method pattern comes under creational pattern.

According to Gang Of Four intent of Factory Method pattern is to Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

SAMPLE CODE:

#include <iostream>

using namespace std;

enum LaptopType { APPLE, DELL, HP };

class Laptop {
public:
    virtual void info() = 0;
};

class Apple : public Laptop {
    void info() {
        cout << "Apple Laptop Approved" << endl;
    }
};

class Dell : public Laptop {
    void info() {
        cout << "Dell Laptop Approved" << endl;
    }
};

class Hp : public Laptop {
    void info() {
        cout << "HP Laptop Approved" << endl;
    }
};

Laptop * getLaptopFactory(LaptopType choice)
{
    Laptop * laptopObj;
    if (choice == APPLE) {
        laptopObj = new Apple();
    }
    else if (choice == DELL) {
        laptopObj = new Dell();
    }
    else if (choice == HP) {
        laptopObj = new Hp();
    }
    else {
        laptopObj = NULL;
    }
    return laptopObj;
}

int main()
{
    Laptop * emp1Laptop;
    emp1Laptop = getLaptopFactory(DELL);
    emp1Laptop->info();

    Laptop * emp2Laptop;
    emp2Laptop =  getLaptopFactory(APPLE);
    emp2Laptop->info();
}

OUTPUT:

Dell Laptop Approved
Apple Laptop Approved

Singleton Design Pattern

Singleton pattern is one of the creational pattern.

According to GoF intent of Singleton pattern is to Ensure a class only has one instance, and provide a global point of access to it.


Code :

#include <iostream>

using namespace std;

class Logger {
public:
    static Logger* getInstance();

private:
    Logger(){}                   //Made private don't to create object via constructor
    Logger(Logger *);            //copy constructor is private so it can't be copied
    Logger* operator=(Logger *); //Assignment operator is private

    static Logger *instance;
};

Logger* Logger::instance = NULL;

Logger* Logger::getInstance() {
    if (instance == NULL) {
        instance = new Logger();
        cout << "Creating New Object "<< endl;
    } else {
        cout << "Utilizing Existing Object " << endl;
    }
    return instance;
}

int main()
{
    Logger *inst1 = Logger::getInstance();

    Logger *inst2 = Logger::getInstance();

    Logger *inst3 = Logger::getInstance();

    return 0;
}

Output:

Creating New Object
Utilizing Existing Object
Utilizing Existing Object


LD_PRELOAD Tutorial

Dynamic linker will load the all the shared library one bye one in any order. LD_PRELOAD  is a environment variable containing libraries that the dynamic linker will load before loading any other libraries.

By using this we can override the function available in the later libraries. Even we can over ride the functions available in C programs libc libraries. Here i demonstrate the usage of LD_PRELOAD with simple example.

Simple C program named as ldmain.c 
#include <stdio.h>
int main()
{
        printf("PID = %d\n", getpid());
        return 0;
}

Above program will print the process id of the current process using libc function getpid.

Compile the above program using gcc compiler and run the program, it will print the process id.
sujinsr@fedo:~/workspace/c $ gcc -o main ldmain.c 

sujinsr@fedo:~/workspace/c $ ./main 
PID = 1082

Now you see how we can override the libc's getpid with our own. Write our own version of the getpid function. Here i named the file as ldpid.c
#include <stdio.h>
int getpid()
{
        printf("My own version of getpid() for testing it will return always 99999\n");
        return 99999;
}

Create the shared object of that function using gcc
sujinsr@fedo:~/workspace/c $ gcc -o ldpid.so ldpid.c -fPIC -shared 

Set the LD_PRELOAD envirnonment as new shared library we created before.
sujinsr@fedo:~/workspace/c $ export LD_PRELOAD=./ldpid.so

Run the program and see our own version of getpid called instead of libc's function.
sujinsr@fedo:~/workspace/c $ ./main 
My own version of getpid() for testing it will return always 99999
PID = 99999

If you want to remove shared library configured to LD_PRELOAD just unset the environment variable like below.
sujinsr@fedo:~/workspace/c $ unset LD_PRELOAD

sujinsr@fedo:~/workspace/c $ ./main
PID = 1638

Cheers !!!!!

hexdump command examples in linux

hexdump:

linux1machine-~/ssdir: cat dumptext.txt
aj14Qy8

Character
linux1machine-~/ssdir: hexdump -c dumptext.txt
0000000   a   j   1   4   Q   y   8  \n
0000008

Install VMWARE Tools in CentOS

1. change to root

su

2. yum install gcc

run vmware without gui

download vix api from vmware site


https://www.vmware.com/support/developer/vix-api/

VIX SDK for Linux 64-bit 


Setting static ip in Linux/Centos/RHEL/

1. login as root

[fedo@dhcppc6 ~]$ su root
Password:
[root@dhcppc6 fedo]#


2. Stop network manager

[root@dhcppc6 fedo]# service NetworkManager stop
Stopping NetworkManager daemon:                            [  OK  ]


Daemonizing Server Process in Linux

If we have the server it has to handle all the request and response without the help of 
user. So better running server process as background is good idea.

We can run the Linux process as foreground or background. A process is called daemon when it running in background
and doing necessary work.

Steps to make Server process as daemon:

1. Create child process and separate from parent - fork()

create child process using fork() system call, then exit parent process. Once parent exits new child process
will child of init process and behave as background process.

pid = fork()
if (pid < 0)
exit(1);

if (pid > 0)
exit(0);

/* child continue as daemon */


2. Make new child process independent - setsid()

When terminal receives signal, all the process connected to this terminal get signal. 
child process created through fork() system call will inherit process group of parent process. All the signal passed
to process group will passed to inherited process. 

daemon server should not get signal from where was started. 

We can make daemon process independent from parent using setsid() system call

setsid() /* get a new process group */

3. Handle standard I/O stream - getdtablesize(), open(), dup(), dup2()

fork system call will inherit all open file descriptor of parent. so close all the unnecessary open file 
descriptor.

for( fds=getdtablesize(); fds >=0; fd--)
close(fds);

standard libraries use standard stream for some work, better close all three standard ( stdin - 0, stdout - 1, stderr - 2)
for safety purpose redirect the out put to /dev/null.

i = open("/dev/null", O_RDWR);
dup(i);
dup(i);

for ease understanding read the man page of 'open', 'dup' & 'dup2'.

4. Change file creation mask - umask()

Most of the server run as root user mode(not mandatory). So it should protect the files it created when it run.
we can change the process privilege using umask system call.

umask(027);

This will restrict file creation mode to 750

5. Change working directory - chdir()

Server should be run from root directory (not mandatory), then only it can see all the files 
from system.

chdir("/");

"/" means root directory.

6. Run single copy of server

For a system it requires only one copy server at a time. File locking is a good method to achieve this by making
other process wait on the file lock. when process terminate lock on this file automatically released then server
which waiting on the lock will start work.

write the pid of the process to file, which will help to know the running pid of the server. 

lfp = open("lockfile.lock", O_RDWR|O_CREAT, 0650);
if (lfp < 0)
exit(1);
if (lockf(lfp, F_TLOCK, 0) < 0)
exit(1);
sprintf(strpid, "%d\n", getpid());
write(lfp, strpid, strlen(strpid));

7. Logging

When server is running some messages should be logged. This will help for developer to debug the server
if any problem arise.

void logging(char *filename, char* log)
{
FILE *fp;
fp = open(filename, "a");
if (fp == NULL) 
return;
fprintf(logfile, "%s\n", log);
fclose(fp);
}

/* log messages as below */
logging("logfile.txt", "This is server log");


Program:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

#define WORKING_DIR "/home/sujin/c"
#define LOCK_FILE "lockfile.lock"
#define LOG_FILE "logfile.log"

void make_daemon();
void logging(char *file, char *log);

void logging(char *file, char *log)
{
        FILE *fp;
        if ((fp = fopen(file, "a")) == NULL)
                return;
        fprintf(fp, "%s\n", log);
        fclose(fp);
}

void make_daemon()
{
        int pid, lockfd, i;
        char pidstr[16];

        pid = fork();
        if (pid < 0) {
                printf("fork error.\n");
                exit(1);
        }
        if (pid > 0)
                exit(0);

        setsid();

        for (i = getdtablesize(); i >= 0; i--)
                close(i);

        i = open("/dev/null", O_RDWR);
        dup(i);
        dup(i);

        umask(027);

        chdir(WORKING_DIR);

        lockfd = open(LOCK_FILE, O_RDWR|O_CREAT, 0640);
        if (lockfd < 0)
                exit(1);

        if (lockf(lockfd, F_TLOCK, 0) < 0)
                exit(1);

        sprintf(pidstr, "%d\n", getpid());
        write(lockfd, pidstr, strlen(pidstr));

}

int main(int argc, char *argv[])
{
        make_daemon();
        sleep(5);
        while(1)
        {
                /* Do server work */
                logging(LOG_FILE, "This is write from main server.\n");
        }

        return 0;
}


I am not full owner of this article. I grabbed some details from other articles. Full credits goes to author of Unix Daemon Server Programming