OOP Design Patterns Summary

Summary of OOPs Design Patterns from GoF Book

Note: Syntax, keywords of C++ used in example snippets.

Download: DesignPatterns_Summary

Creational Patterns

Singleton

Object is created only once using a static Create() method; new is not called directly.

First call of Create() method creates a static object using new.

Subsequent calls to the Create() method returns the pointer to static object already created.

Factory Method / Virtual Constructor

Objects are created using Create method instead of calling new directly.

BaseClass: abc

DerivedClasses: A,B,C

Factory:

abc CreateChar(char id) {

switch(id) {

case ‘a’: return new A();

case ‘b’: return new B();

case ‘c’: return new C();

}

}

Abstract Factory

BaseClass has CreateChar, CreateNum virtual functions

Factory1:

abc CreateChar() {

return A;

}

num CreateNum() {

return N1;

}

Factory2:

abc CreateChar() {

return B;

}

num CreateNum() {

return N2;

}

Builder

It takes many steps to create a concrete object.

Eg. Creating a tree, linked list, etc.

Prototype

Clone() method is used to copy self

Concrete objects are cloned from prototype and can be cloned again.

Inheritance: Derived class object can access base class variables, functions

Prototyping: Cloned object can access protype class variables only.

Structural Patterns

Adapter

Convert interface of a class as clients expect.

Make systems work together after they are designed.

Bridge

Similar to adapter but the interface is known in advance.

class systemA {

systemB *s;

void set(systemB *ss) { s = ss; }

void exec() { s->run(); }

}

Composite

Creating a hierarchical tree

Every node can create its own child(branch/leaf).

Each branch/leaf can be of a different type.

Decorator / Wrapper

Similar to Adapter. But interface doesn’t change. Wrapper can do additional operations.

class wrapper {

original o;

void func() {

decorate();

o.func();

}

}

Façade

Provide a higher level interface to combine many complex interfaces.

Eg. Compile() =  Scan() + Parse() + ByteCode() + Interpret()

Proxy / Surrogate

Smaller object acts on behalf of a larger object.

Eg. Document with an image. Proxy object can have only path to image file, pointer to ImageDisplay object. ImageDisplay object need not created unless Document.display() is called.

Flyweight

Use sharing to improve efficiency.

Example:

Not-Efficient:

class character {

char c;

int row, col;

}

Instead of storing a character object for every position,

Store position of every character in the alphabet.

Efficient:

class position {  int row, col; }

class character {

char c;

position p_array[];

}

 

Behavioral Patterns

 

Chain of Responsibility

Request is passed along a chain until an object finally handles it.

Split complex tasks into simpler tasks and make the system modular.

Eg. BuildHouse() calls BuildRooms();

BuildRooms() calls BuildFloors(), BuildWalls();

BuildWalls() calls BuildDoors(), BuildWindows().

Command

Encapsulate a request as an object. Each request type can have a different command object.

Iterator / Cursor

Provide a way to access elements without exposing underlying implementation.

Example:

int array[10]; // Every element can be accessed as array[i];

Iterator implementation:

class iterator {

int array[10];

int i=0;

int get() { return array[i]; i++; }

int end() { if(i<10) return 0; else return 1; }

}

Interpreter

Create a tree and execute each node recursively starting from root.

Mediator

Defines an object that encapsulates how a set objects interact. Objects need not interact by referring the other object explicitly. In Bridge pattern, two systems know the interface of the other. In Mediator pattern each system knows its interface to Mediator object.

Memento / Token

Store internal state of an object to restore later.

Eg. Moving a cursor on screen needs the position fields to be changed without changing other fields.

Memento object can store the position using get_position() method of cursor.

Modify memento with new position. Again use the memento to set_position() of cursor.

Instead of accessing internal variables of cursor, get, set methods are used along with memento.

Observer / Publish-Subscribe

Every subject keeps a list of observers. Any change in the subject updates all the observers.

Eg. Same Data can be represented as table, bar-graph, pie-chart.

State

Equivalent of having a state object for every case in a switch statement.

A state object implements task in current state, returns name of next state.

Client initializes its state-variable, calls methods in every state, changes state variable after every state.

Strategy / Policy

Do similar task using different algorithms. The family of algorithms are encapsulated and made interchangeable.

Template-Method

Define skeleton of algorithm in an operation, Let sub-class define the algorithm without changing the algorithm’s structure.

Visitor

Create a parallel tree with a visitor on each node.

Eg. Main tree does execution operation of a compiler. Visitor objects corresponding to each node does type-checking / syntax-checking.

 

  Design Patterns Summary
Creational Pattern Constructs
Singleton Object only once
Factory Method Object by ID
Abstract Factory Group of Objects by ID
Builder Object in many steps
Prototype Object by cloning another
Structural Pattern Connects
Adapter Two existing systems with different interfaces
Bridge Two systems by defining an interface
Composite Using same interface to create a tree
Wrapper To Object with same interface but more functions
Façade Multiple objects by merging interfaces
Flyweight Objects by separating fields that vary lesser
Proxy Object with light-weight interface
Behavioral Pattern Encapsulates
Chain-of-responsibility Modular sub-tasks to perform a complex task
Command Requests to perform different tasks
Iterator Private Data & Implementation with simpler interface
Interpreter Different tasks assigned to objects of a tree
Mediator Interfaces to different systems
Memento Interfaces to change private state variables
Observer Interface to tasks of different observers within broadcaster
State State specific tasks and next-state logic
Strategy Family of inter-changeable algorithms
Template Steps in algorithms by defining a skeleton
Visitor Auxiliary tasks for visitors of every node of a tree
Advertisements

System Verilog Singleton Example

Purpose of a singleton:
To have a class which has only one instance(object)
All the objects of this class refer to same global object
that is created only once
This design pattern provides a mechanism for providing
namespaces to global variables

Download here. singleton-design-pattern
C++ example for singleton design pattern: click here

System Verilog example for singleton design pattern

// Filename  : singleton.sv
// Author    : A.G.Raja
// License   : GPL
// Website   : https://agraja.wordpress.com

module tb;

class Singleton;
// object that is created only once
extern static Singleton single;
// constructor that is called only once
extern function new;
// method to get object
extern function Singleton get_instance;
// data to check the functionality
int data;
endclass

initial Singleton::single = null;

function Singleton::new;
data = 14;
endfunction

function Singleton Singleton::get_instance;
// call the constructor for the first time
// if the object has been created already
// return reference to the object already created
if(single==null) single = new;
// return the reference to the object
return single;
endfunction

Singleton s, t;

initial begin
// don’t use s= new;
// since it will create new instances
// instead use the get_instance method
s = s.get_instance();
t = t.get_instance();
$display(“initial value of s.data  = “,s.data);
s.data = 25;
$display(“modified value of s.data = “,s.data);
$display(“value of t.data          = “,t.data);
end
endmodule

Result:
initial value of s->data  = 14
modified value of s->data = 25
value of t->data          = 25
Download here. singleton-design-pattern

C++ Singleton Example

Download here.  singleton-design-pattern

Purpose of a singleton:
To have a class which has only one instance(object)
All the objects of this class refer to same global object
that is created only once
This design pattern provides a mechanism for providing
namespaces to global variables

C++ example for singleton design pattern

// Filename  : singleton.cpp
// Author    : A.G.Raja
// License   : GPL
// Website   : https://agraja.wordpress.com

#include <iostream>

using namespace std;

class Singleton {
// constructor that is called only once
Singleton();
// object that is created only once
static Singleton *single;
public:
// method to get object
Singleton* get_instance();
// data to check the functionality
int data;
};

Singleton* Singleton::single = NULL;

Singleton* Singleton::get_instance() {
// call the constructor for the first time
// if the object has been created already
// return reference to the object already created
if(single==NULL) single = new Singleton();
return single;
}

Singleton::Singleton() {
data = 14;
}

int main() {
Singleton *s, *t ;
s = s->get_instance();
cout<<“initial value of s->data  = “<<s->data<<endl;
s->data = 25;
cout<<“modified value of s->data = “<<s->data<<endl;
t = t->get_instance();
cout<<“value of t->data          = “<<t->data<<endl;
}
// end of file singleton.cpp

Result:
initial value of s->data  = 14
modified value of s->data = 25
value of t->data          = 25

Download here.  singleton-design-pattern

C++ string, wstring conversion functions

Download here. string-wstring-conversion-functions

// Filename    : string_wstring.cpp
// Author      : A.G.Raja
// License     : GPL
// Website     : https://agraja.wordpress.com

#include <iostream>

using namespace std;

string wstring2string(wstring wstr) {
string str(wstr.length(),’ ‘);
copy(wstr.begin(),wstr.end(),str.begin());
return str;
}

wstring string2wstring(string str) {
wstring wstr(str.length(),L’ ‘);
copy(str.begin(),str.end(),wstr.begin());
return wstr;
}

int main() {
wstring wstr = string2wstring(“raja”);
string str = wstring2string(wstr);
cout<<str<<endl;
}

Download here. string-wstring-conversion-functions

C++ String Getline Class

Download here. getline

Features of the below string getline class

1) Can be used like getline function for streams

2) Can have multiple delimiters as opposed to the getline function for streams

3) Delimiter need not be single char. It can be a string

4) Pointer to current position in the string is automatically incremented

similar to that in stringstream

5) It is possible to rewind the pointer position to zero using the rewind() method.

6) It is also possible to get single char at the current position of pointer from the string

7) It is possible to get single char at current pointer position if it is one of the

characters of the list.  This is an optional argument to the get method

8) stream getline feature can be realized by calling the getline method of this

class without passing any arguments. No arguments to getline method defaults to

newline char as delimiter

// File : Getline.hh
// Author : A.G.Raja
// License : GPL
// Website : https://agraja.wordpress.com

#include <iostream>

using namespace std;

class Getline {
string text, buffer;
int pos,p;
public:
int str(string txt) {
pos = 0;
this->text = txt;
}
string getline(string delim = “\n”, int delim_type = 1);
char get(string delim = “”);
int unget(int decr = 1) {
pos -= decr;
}
int end() {
if(pos>=text.size()) return 1;
else return 0;
}
int rewind() {
pos = 0;
}
};

string Getline::getline(string delim, int delim_type) {
p = delim_type ? text.find(delim,pos)
: text.find_first_of(delim,pos);
if(p!=-1) {
buffer = text.substr(pos,p-pos);
pos = delim_type ? p+delim.length() : p +1;
} else {
buffer = text.substr(pos);
pos += buffer.length();
} return buffer;
}

char Getline::get(string delim) {
if(delim.empty() and pos<text.size()) return text[pos++];
if(delim.find(text[pos])!=-1) {
pos++;
return text[pos-1];
}
return 0; // must
}

// End of File Getline.hh

// File : test_Getline.cpp
// Author : A.G.Raja
// License : GPL
// Website : https://agraja.wordpress.com

#include <iostream>
#include “Getline.hh”

using namespace std;

int main() {
Getline g;
g.str(“Hi, my name is Raja\nI’m an Engineer”);
// Get the substring terminated by “y na”
cout<<g.getline(“y na”)<<endl;
// Result: “Hi, m”

// Get substring terminated by first of “sji”
cout<<g.getline(“sji”,0)<<endl;

// Get line terminated by ‘\n’
cout<<g.getline()<<endl;
// Result: “s Raja”

// Get single char at current position of pointer
cout<<g.get()<<endl;
// Result: “I”

// Get a char at current position of pointer
// if it is in the list “_$%’#”
cout<<g.get(“_$%’#”)<<endl;
// Result: “‘”

// Unget single char, unget 4 chars
g.unget(); g.unget(4);
}

Download here. getline

C program to trim blank spaces

#include <stdio.h>

void copy(char *to, char *from);

int main(void)
{

char str[80];

copy (str,” this ia a test “);

printf(“without spaces:%s”,str);

return 0;

}

void copy(char *to, char *from)

{

const char *p; char *q;

for(p=from,q=to;*p != ‘ ‘; p++)

// space between quotes in the above statement
{

if (*p != ‘ ‘) { *q=*p; q++; }

}

*q = ”;

}

// Download here.

// trim.doc

Tips: This function can be modified to find and replace a char.

See this page for an example Find and Replace

See this page for string replace: string replace

GCC Include Files Path

GCC looks in several different places for headers.

On a normal Unix system, if you do not instruct it otherwise, it will look for headers requested with #include <file> in:

/usr/local/include
libdir/gcc/target/version/include
/usr/target/include
/usr/include
You can add to this list with the -Idir command line option.

Below is a small demo

///////////     defines.c   ////////
#include <stdio.h>
#include <defines.h>
int main()
begin
    printf("hellon");
    return 0;
end

This requires the folowing header file

///////     headers/defines.h   ///////////
#define begin {
#define end }
//////  save this file in directory named headers

Compile defines.c as below

[raja@AGRAJA ~] gcc defines.c -Iheaders