Showing posts with label Design-Patterns. Show all posts
Showing posts with label Design-Patterns. Show all posts

Friday, June 3, 2016

Design a Simple Chat Server

Solution:

                                                         Simple Chat Server

Chat application can be described as a connection-oriented service because a user establishes a connection and maintains that connection. send and receive text,image and Audio-Video files for the duration of the session.

There should not be a confusion from Web Protocol because in web, the browser asks for a page and the server sends it and then connection is closed but in Chat application client need to maintain the connection for the session.

Basics of Chat Server:

  • Server Class which can be started as s standalone application basically you can say Listener.
  • Mechanism for accepting the connections.
  • Mechanism for reading and writing data on server side.
  • Client class which can be started as a standalone application.
  • A thread class which can creates separate thread for each client.
  • Mechanism for reading  and writing data on client side.
  • Closing the chat connections.
Server Class(Listener Class) : 

public class Server
{
public Server(int port) throws IOException
{
listen(port);
}
private void listen(int port)
{
// will explain in future
}
}

Server Thread:

import java.net.Socket;
public class ServerThread extends Thread
{
public ServerThread(Server server,Socket socket)
{
this.server=server;
this.socket=socket;

start(); //start the thread
}

}

Client Class Method:

public Client(String host,int port)
{
setLayout(new BorderLayout);
add("North",tf);
add("Center",ta);

tf.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
processMesssage(e.getActionCommand());
}
});

}

Complete Code Implementation:

import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Hashtable;

/**
 *
 */

/**
 * @author Abhinaw.Tripathi
 *
 */
class Server
{
  private ServerScocket ss;
  private Hashtable OutputStreams =new Hashtable<>();
  public Server(int port) throws IOException
  {
listen(port);
}
private void listen(int port)
{
ss=new ServerSocket(port);
System.out.println("Listening on" + ss);
while(true)
{
Socket s=ss.accept();
System.out.println("Connection from " + s);
DataOutputStream dout= new DataOutputStream(s.getOutputStream());
OutputStreams.put(s, dout);

new ServerThread(this,s);
}
}

Enumeration getOutputStreams()
{
return OutputStreams.elements();
}

void sendToAll(String message)
{
synchronized (OutputStreams)
{
for(Enumeration e=getOutputStreams();e.hasMoreElements();)
{
DataOutputStream DOUT =(DataOutputStream)e.nextElement();
try
{
DOUT.writeUTF(message);
}
catch(IOException ie)
{
System.out.println(ie);
}
}
}
}

void removeConnection(Socket s)
{
synchronized (OutputStreams)
{
System.out.println("Removing connection " + s);
OutputStreams.remove(s);
try
{
s.close();
}
catch(Exception e)
{
System.out.println("Error closing " +s);
}
}
}
}

class ServerThread extends Thread
{
  private Server server;
  private Socket socket;
 
  public ServerThread(Server server,Socket socket)
  {
this.server=server;
this.socket=socket;
start();
}
 
  public void run()
  {
  try
  {
  DataInputStream din=new DataInputStream(socket.getInputStream());
  String message=din.readUTF();
  System.out.println("Sending " +message);
  server.sendToAll(message);
  }
  catch(EOFException e)
  {
 
  }
  catch (IOException e)
  {

}
  finally
  {
  server.removeConnection(socket);
  }
  }
}

class Client extends Panel implements Runnable
{
  private TextField tf=new TextField();
  private TextArea ta=new TextArea();
  private Socket socket;
  private DataOutputStream dout;
  private DataInputStream din;

  public Client(final String host,final int port)
  {
 setLayout(new BorderLayout());
 add("North",tf);
 add("Center",ta);
 tf.addActionListener(new ActionListener()
 {
@Override
public void actionPerformed(ActionEvent arg0)
{
try
{
socket =new Socket(host,port);
System.out.println("connected to " +socket);
din=new DataInputStream(socket.getInputStream());
dout=new DataOutputStream(socket.getOutputStream());
new Thread().start();
}
catch (IOException e)
{
e.printStackTrace();
}

}
});
  }

@Override
public void run()
{

while(true)
{
try
{
String message=din.readUTF();
ta.append(message + "\n");
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
 
private void processMessage(String message)
{
try
{
dout.writeUTF(message);
tf.setText(" ");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


}

class ClientApplet extends Applet
{
public void init()
{
String host=getParameter("host");
int port=Integer.parseInt(getParameter("port"));
setLayout(new BorderLayout());
add("Center",new Client(host, port));
}
}


public class SimpleChatServerTest {

/**
*
*/
public SimpleChatServerTest() {
// TODO Auto-generated constructor stub
}

/**
* @param args
*/
public static void main(String[] args)
{
int port=Integer.parseInt(args[0]);
try
{
new Server(port);
}
catch (IOException e)
{
e.printStackTrace();
}
}

}




Design a Cache mechanism which uses LRU(Least Recently Used) in java

Solution Description:

The Processing costs for selecting a value from a database-table is high compared to the cost having the value already in memory.So there should be some mechanism that keeps often used values in your application instead getting these values from resource somewhere outside.

But there is a point when using cache in java is the size of the cache;when chache grows too big the java garbage collector has to cleanup more often or our application crashes with a out of memory error.

So we can implement LRU using "LinkedHashMap" class allows us to implement both an LRU and FIFO queues almost without coding.

Why LinkedHashMap? we are using?.
Because the map to become an LRU map. That's because  the map is ordered by access-order.

public LinkedHashMap(int initialCapacity,float loadFactor,boolean accessOrder)

Implementation:

import java.util.LinkedHashMap;

/**
 *
 */

/**
 * @author Abhinaw.Tripathi
 *
 */
public class LRUCache extends LinkedHashMap
{

private static final long serialVersionUID =1L;
private final int capacity;
private long accessCount = 0;
private long hitCount =0;

public LRUCache(int capacity)
{
this.capacity =capacity;
}

public Object get(Object key)
{
accessCount++;
if(super.containsKey(key))
{
hitCount++ ;
}
Object value=super.get(key);
return value;
}

public boolean containsKey(Object key)
{
accessCount ++ ;
if(super.containsKey(key))
{
hitCount++ ;
return true;
}
else
{
return false;
}
}

protected boolean removeEldesEntry(Entry eldest)
{
return size() > capacity ;
}

public long getHitCount() {
return hitCount;
}

public long getAccessCount() {
return accessCount;
}

}

Note: There is a Catch here.What if the interviewer does not allow us to use"LinkedHashMap"?
I am leaving on you guys to solve without "LinkedHashMap".

Design a Cinema Management System.

Solution:

As we know any cinema associated with a number of theaters and each theater contains a set of rows with a number of seats and also each seats will have specification.

Implementation:

import java.io.Serializable;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

/**
 *
 */

/**
 * @author Abhinaw.Tripathi
 *
 */
class SeatSepecification implements Serializable,Cloneable
{
  private HashMap<String,Object> features;
  public SeatSepecification()
  {
features =new HashMap<>();
  }

  public void addFeature(String featureLabel,Object featureValue) throws  InvalidParameterException
  {
 if(featureValue == null)
 throw new InvalidParameterException("fetaure value cannot be null");
 else
  features.put(featureLabel, featureValue);
  }

  public Object checkFeature(String featureLabel)
  {
 return features.get(featureLabel);
  }

  public boolean match(SeatSepecification givenSpec)
  {
String currFeature;
if(givenSpec == null)
return false;
else
{
Iterator it=givenSpec.features.keySet().iterator();
while(it.hasNext())
{
currFeature=(String)it.next();
if(!features.get(currFeature).equals(givenSpec.features.get(currFeature)))
return false;
}
return true;
}
  }

  public  SeatSepecification clone()
  {
  try
  {
  SeatSepecification c=(SeatSepecification)super.clone();
  c.features=new HashMap<>();
  Iterator it=features.keySet().iterator();
  while(it.hasNext())
  {
  String currFeatureLabel=(String)it.next();
  Object currentFeatureValue=features.get(currFeatureLabel);
  c.features.put(currFeatureLabel, currentFeatureValue);
  }
  return c;
  }
 
  catch(CloneNotSupportedException e)
  {
  return null;
  }
  }

}

class Seat implements Serializable,Cloneable
{
  private SeatSepecification spec;
  private String id;

  public Seat(String id) {
this.id=id;
spec=new SeatSepecification();
}

  public SeatSepecification getSpec() {
return spec;
}
public void setSpec(SeatSepecification spec) {
this.spec = spec;
}
public String getId() {
return id;
}

public void setSeatSpecification(String featureLabel,Object featureValue) throws InvalidParameterException
{
spec.addFeature(featureLabel, featureValue);
}

public boolean match(SeatSepecification givenSpec)
{
return spec.match(givenSpec);
}

public boolean isReserved()
{
return true;
}

public Seat clone()
{
Seat cloneSeat=new Seat(id);
return cloneSeat;
}

}

class RowOfSeats implements Serializable,Cloneable
{
 private HashMap<String,Seat> seats;
 private String rowId;
 private int numOfSeats;
 ArrayList<String> keys;

 public RowOfSeats(String rowId,int numOfSeats) throws InvalidParameterException
 {
seats=new HashMap<>();
int i=0;
Seat s;

while(i<numOfSeats)
{
s=new Seat(Integer.toString(i));
seats.put(s.getId(), s);
i++;
}

keys =new ArrayList<>();
this.rowId =rowId;
this.numOfSeats=numOfSeats;
 }

 public void setSeatFeature(String seatID,String featureLabel,Object fetureValue) throws InvalidParameterException
 {
if(seats.containsKey(seatID))
{
Seat s=seats.get(seatID);
s.setSeatSpecification(featureLabel, fetureValue);
}
else
{
throw new InvalidParameterException("no seat " + seatID);
}
 }

 public String getRowId()
 {
return rowId;
 }

 public int getNumOfSeats()
 {
return seats.size();
 }

 public void addSeat()
 {
Seat s;
numOfSeats +=1;
s=new Seat(Integer.toString(numOfSeats));
seats.put(s.getId(), s);
keys.add(Integer.toString(numOfSeats));
 }

 public void removeSeat(String seatID) throws InvalidParameterException
 {
if(seats.containsKey(seatID))
{
seats.remove(seatID);
}
else
{
throw new InvalidParameterException("The specific seat not found!!!!");
}
 }

 public RowOfSeats clone()
 {
RowOfSeats newRowOfSeats=(RowOfSeats) super.clone();
Iterator it=seats.keySet().iterator();
for(int i=0;i<=keys.size();i++)
{
String seatID=keys.get(i);
while(it.hasNext())
{
newRowOfSeats.put(seatID,seats.get(seatID).clone());
}
}
return newRowOfSeats;
 }

}

public class CinemaManagementSystemTest {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

}


}

Need to add few more classes such as

1)SeatingChart Class
2)Theater Class
3)Movie Class
4)CineGoer Class=basically models a cinema goer.
5)Show Class
6)ReservationSpecification Class
7)Reservation Class
8)CinemaManagmentSystem

These are all classes which will be implemented using Serialization and Clonable .





Design Library Management System?

Solution:

The basic components of the library are: library items and mechanism for giving books to users.Please find the implementation below.

Implementation:

import java.util.HashMap;
import java.util.Map;

/**
 *
 */

/**
 * @author Abhinaw.Tripathi
 *
 */

class Book
{
  private String thAuthor,theTitle,pageCount,year,edition;

  public Book(String author,String title,String pages,String yearPublished,String bookEdition)
  {
this.edition=bookEdition;
this.thAuthor=author;
this.pageCount=pages;
this.theTitle=title;
this.year=yearPublished;
  }

public String getThAuthor() {
return thAuthor;
}
public void setThAuthor(String thAuthor) {
this.thAuthor = thAuthor;
}
public String getTheTitle() {
return theTitle;
}
public void setTheTitle(String theTitle) {
this.theTitle = theTitle;
}
public String getPageCount() {
return pageCount;
}
public void setPageCount(String pageCount) {
this.pageCount = pageCount;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getEdition() {
return edition;
}

}

interface LibraryItem
{
  public String getID();
  public boolean checkOut(String holder);
  public String getHolder();
}

class LibraryBook extends Book implements LibraryItem
{
private String theID;
private String theHolder;

public LibraryBook(String author, String title, String pages,String yearPublished, String                  bookEdition,String id)
{
super(author, title, pages, yearPublished, bookEdition);
theID=id;
}

@Override
public String getID()
{
// TODO Auto-generated method stub
return null;
}

@Override
public boolean checkOut(String holder)
{
// TODO Auto-generated method stub

if(theHolder == null)
{
theHolder=holder;
return true;
}
return false;
}

@Override
public String getHolder() {
// TODO Auto-generated method stub
return theHolder;
}

}

class Library
{
  private Map items;

  public Library()
  {
items=new HashMap();
  }

  public void add(LibraryItem theItem)
  {
 items.put(theItem.getID(), theItem);
  }

  public void checkout(String id,String holder)
  {
 LibraryItem item=(LibraryItem)items.get(id);
 item.checkOut(holder);
  }

  public String getHolder(String id)
  {
 LibraryItem item=(LibraryItem)items.get(id);
 return item.getHolder();
  }

}


public class LibraryManagementTest {

/**
*
*/
public LibraryManagementTest() {
// TODO Auto-generated constructor stub
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Book book=new Book("Abhinaw Tripathi", "Design-Pattern", "100", "2016", "2016");
book.getEdition();
book.getPageCount();
book.getTheTitle();

}

}

Thursday, June 2, 2016

Design Interview Question - Design a Grocery Store.

Problem: Design a Grocery Store.

Answer:

For this what we need is:

  • A customer class
  • A store Class
  • A GroceryItem of various sorts
  • A cashier


/**
 * @author Abhinaw.Tripathi
 *
 */

class Customer
{
public GroceryItem[] myshoppinBasket =new GroceryItem[20];
Random random=new Random();
double myMoney=100.00;



public void shop(GroceryStore store)
{
selectGroceries(store);
checkOut(store);
}

public void checkOut(GroceryStore store)
{
Cashier cashier=store.getCasiCashier();
 double total=cashier.getBill(myshoppinBasket);
 myMoney=myMoney - total;
 cashier.pay(total);

}

public void selectGroceries(GroceryStore store)
{

int itemsInmybasket=0;
for(int i=0;i<store.KINDS_OF_ITEM;i++)
{
for(int j=0;j<3;j++)
{
if(random.nextInt(2) == 1)
{
myshoppinBasket[itemsInmybasket]=store.item[i];
store.itemCount[i] =store.itemCount[i]-1;
itemsInmybasket=itemsInmybasket + 1;
}
}
}
}

}

class Cashier
{
GroceryStore myStore;
public void takePosition(GroceryStore store)
{
myStore=store;
}


public double getBill(GroceryItem[] item)
{
double total=0;
int itemNUmber=0;
while(item[itemNUmber]!=null)
{
total=total +item[itemNUmber].price ;
System.out.println(item[itemNUmber].name + " " + item[itemNUmber].price);
itemNUmber= itemNUmber+1;
}
System.out.println("Total" + total);
return total;
}

public void pay(double amount)
{
myStore.money=myStore.money + amount;
}

}

class GroceryItem
{
 public String name;
 public double price;
 public GroceryItem(String name,double price) {

this.name=name;
this.price=price;
}

}

class Store
{
  Cashier myCashier;

  public Cashier getCashier()
  {
 return myCashier;
  }

}


public class GroceryStore
{
Cashier myCashier;
public int KINDS_OF_ITEM=4;
public GroceryItem[] item=new GroceryItem[KINDS_OF_ITEM];
public int[] itemCount=new int[KINDS_OF_ITEM];
double money =1000.00;


public GroceryStore()
{
item[0]=new GroceryItem("milk",2.12);
item[1]=new GroceryItem("butter",2.502);
item[0]=new GroceryItem("eggs",1.12);

for(int i=0;i<KINDS_OF_ITEM;i++)
{
itemCount[i]=50;
}
}

public void hire(Cashier cashier)
{
myCashier=cashier;
cashier.takePosition(this);
}

public Cashier getCasiCashier()
{
return myCashier;
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

GroceryStore store=new GroceryStore();
Cashier cashier=new Cashier();
Customer customer=new Customer();
customer.shop(store);
store.hire(cashier);

}


}

Simple Design Pattern Interview Questions

Problem-1: Can you explain about access specifiers in java?

Answer: In java , classes,variables,methods and constructor can have access specifiers.There are 4 types of access specifiers.

  1. private
  2. protected
  3. public
  4. default or No specifier or none
There is a point to be noted about constructors in java are treated differently than methods because constructor are not considered a class member.

Class Members are made of two things:
  • Class's variable
  • Class' methods
Problem-2 : Given a database application,Can you think of classes to generate unique sequence numbers?

Answer: Here we can use Singleton Pattern to create a counter to provide unique sequential numbers.This is can be used as primary keys in database.

public class SequenceNumber
{
  private static SequenceNumber instance;
  private static int count;
  private SequenceNumber(){
    count=0;
 }
public static synchronized SequenceNumber getInstance()
{
   if(instance==null)
 {
  instance =new SequenceNumber();
 }
  return instance;
}

public synchronized int getNext()
{
  return ++count;
}

}

Find k-th smallest element in BST (Order Statistics in BST)

Solution Approach:

By using In order traversal of BST retrieves elements of tree in the sorted order. The in order traversal uses stack to store to be explored nodes of tree (threaded tree avoids stack and recursion for traversal). The idea is to keep track of popped elements which participate in the order statics.

Implementation:

public int kthSmallest(TreeNode root, int k) 
{
    Stack<TreeNode> stack = new Stack<TreeNode>();
 
    TreeNode p = root;
    int res = 0;
 
    while(!stack.isEmpty() || p!=null)
{
        if(p!=null)
{
            stack.push(p);
            p = p.left;
        }
else
{
            TreeNode t = stack.pop();
            k--;
            if(k==0)
                res = t.val;
            p = t.right;
        }
    }
 
    return res;
}

We can in order traverse the tree and get the kth smallest element. 
Time complexity: O(n) where n is total nodes in tree.



Given a circular linked list,implement an algorithm which returns the node at the beginning of the loop.

Solution Approach:


  1. Create two pointers ,Fast Pointer and Slow Pointer.
  2. Move Fast Pointer at a rate of 2 and slow pointer at rate of 1.
  3. When they collide ,move slow pointer to linkedlisthead.keep fast pointer where it is.
  4. Move slow pointer and fast pointer at a rate of one step.return the new collision point.

Implementation:

public LinkedListNode FindBeginning(LinkedListNode head)
{
LinkedListNode slow=head;
LinkedListNode fast=head;

while(fast! =null && fast.next !=null)
{
slow =slow.next;
fast=fast.next.next;
if(slow==fast){ // collision
break;
}
}

if(fast == null || fast.next == null)  // no metting point means no loop
return null;

slow=head;
while(slow!=fast)
{
slow=slow.next;
fast=fast.next;
}

}
return fast;


}

Wednesday, June 1, 2016

Flyweight Pattern example java

Flyweight reduces the cost of creating and manipulating a large number of similar objects.Flyweight is used when there is a need to create large number of objects which are in similar nature.Large number of objects consumes high memory and flyweight design pattern gives a solution to reduce the load on memory by sharing objects.It is achieved by isolating object properties into two types intrinsic and extrinsic .

Intrinsic and Extrinsic State:

Create only 25 objects for mapping every unique characters. these 26 objects will have intrinsic state as its character.that is object '"a" will have state as character "a" .then what happens to color ,font and size? those are the extrinsic state and will be passed by client code.26 objects will be in store;client code will get the needed character/object and pass the extrinsic state to it with respect to the context.with respect to context means '''a" in first line may com in red color and same character may com in blue in different line.

When to use Flyweight Design Pattern:


  • Need to create large number of objects.
  • Because of the large number when memory cost is a constraint.
  • When most of the object attribute can be made external and shared.
  • Its better when extrinsic state can be computed rather than stored.

Proxy Design Pattern in java tutorial

What is Proxy Design Pattern?

First of all its a structural pattern and Proxy means in place of.In our collage times we gave proxy in place of or on behalf of are literal meanings of proxy.There are many different flavors of proxy depending on its purpose.we may have a protection proxy to control access rights to an object.

For Example:

Let say you want to attach  an image with an e-mail .now suppose this email has to be sent to millions of consumers in an e-mail campaign.Attaching the image and sending along with the e-mail will be very heavy operation.

So what we can do instead send the image as a link to one of the servlet. The Place Holder of the image will be sent.Once the email reaches the consumer the image place holder will call the servlet and load the image at run time from server.

Now when to use Proxy Pattern:

It is used when we need to represent a complex object with a simpler one.If creation of object is expensive,its creation can be suspended till the necessity arises  and till then a simple object can represent it.The Simple Object is called the Proxy for the complex Object.

Implementation:

/**
 * @author Abhinaw.Tripathi
 *
 */

interface Image
{
 public void showImage();
}

class RealImage implements Image
{
public RealImage(URL url)
{
loadImage(url);
}
private void loadImage(URL url)
{
// operation to load image
}
@Override
public void showImage()
{
// TODO Auto-generated method stub
//display the image

}
}

class ProxyImage implements Image
{

private URL url;
public ProxyImage(URL url) {
this.url=url;
}


public ProxyImage(String string) {
// TODO Auto-generated constructor stub
}


@Override
public void showImage() {
// TODO Auto-generated method stub
RealImage real=new RealImage(url);
real.showImage();
}
 
}

public class ProxyPatternTest {

/**
*
*/
public ProxyPatternTest() {
// TODO Auto-generated constructor stub
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

     Image img1=new ProxyImage("testfolder/image1.png");
     Image img2=new ProxyImage("testfolder/image2.png");
     img1.showImage();  // you can do something like this.
}

}

Tuesday, May 31, 2016

Design Pattern Composite Design Pattern tutorial example java

What is Composite Design Pattern?

A composite pattern is a collection of objects and they may be either a composite or just a primitive object.such as programmers develop systems in which a component may be an individual object or it may represent a collection of objects.
The composite pattern allows  us to build complex objects by recursively composing similar objects in a tree-like manner.

When to use Composite Design Pattern:


  • Manipulating  a single object should be as similar to manipulating a group of objects.
  • Recursive formation and tree structure for composition should be noted.

Implementation:

import java.util.ArrayList;
import java.util.List;

/**
 *
 */

/**
 * @author Abhinaw.Tripathi
 *
 */

interface FileComponent
{
  public void printName();
}

class LeafFile implements FileComponent
{
  private String fileName;
public LeafFile(String name)
{
this.fileName=name;
}

@Override
public void printName() {
// TODO Auto-generated method stub
System.out.println("File Name:" +fileName);
}

}

class Directory implements FileComponent
{
private String fileName;
private List files=new ArrayList<>();

public Directory(String name) {
this.fileName=name;
}

void add(FileComponent obj)
{
files.add(obj);
}

@Override
public void printName() {
// TODO Auto-generated method stub
System.out.println("Directory Name :" + fileName);
for(int i=0;i<files.size();++i)
{
FileComponent obj=(FileComponent)files.get(i);
obj.printName();
}
}

}

public class CompositeDesignTest {

/**
*
*/
public CompositeDesignTest() {
// TODO Auto-generated constructor stub
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

Directory one =new Directory("test123"),
two=new Directory("test456"),
three=new Directory("test789");

LeafFile a=new LeafFile("a.txt"),
b=new LeafFile("b.txt"),
c=new LeafFile("c.txt"),
d=new LeafFile("d.txt"),
e=new LeafFile("e.txt");

one.add(a);
one.add(two);
one.add(b);
two.add(c);
two.add(d);
two.add(three);
three.add(e);
one.printName();

}

}

Friday, May 27, 2016

Strategy Design Pattern tutorial example java

What is Strategy Design Pattern?

Strategy pattern is used when we want different algorithms needs to be applied  on objects.This pattern where algorithms can be selected at runtime.Strategy pattern is also known as the "Policy Pattern" .

For Example:

A mode of transportation to an airport is an example of this pattern because you have multiple options  such as driving your own car,by taxi,b bus etc.

When to use Strategy Pattern:

we can apply Strategy pattern when we need different variants of an algorithm and these related classes differ only in their behavior.


Implementation:

/**
 * @author Abhinaw.Tripathi
 *
 */

interface SortInterface {
public void sort(int[] array);
}

class QuickSort implements SortInterface {

@Override
public void sort(int[] array) {
// TODO Auto-generated method stub
// do quick sort logic here
}

}

class BubbleSort implements SortInterface {

@Override
public void sort(int[] array) {
// TODO Auto-generated method stub
// do Bubble sort logic
}

}

abstract class Sorter {

private SortInterface strategy;

public void setSorter(SortInterface strtegy) {
this.strategy = strtegy;
}

public SortInterface getSorter() {
return this.strategy;
}

abstract void doSort(int[] listToSort);
}

class MySorter extends Sorter {

@Override
void doSort(int[] listToSort) {
// TODO Auto-generated method stub
getSorter().sort(listToSort);
// other things to do
}

}

public class StrategyTest {

/**
*
*/
public StrategyTest() {
// TODO Auto-generated constructor stub
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

int[] listToBeSorted = { 18, 26, 26, 12, 127, 47, 62, 82, 3, 236, 84, 5 };
MySorter mySorter = new MySorter();
mySorter.setSorter(new BubbleSort());
mySorter.doSort(listToBeSorted);
mySorter.setSorter(new QuickSort());
mySorter.doSort(listToBeSorted);

}

}

Design Pattern - Sate Design Pattern tutorial example java

What is State Design Pattern?

The sate design pattern is a behavioral  object design pattern.The idea behind the state patterns is to change object behavior depending on its state.State Pattern allows objects to behave differently depending on internal state that is Context.The context can have a number of internal states whenever the request method is called on the Context,the message is delegated to the State to handle.

For Example:
The control panel of a simple media player could be used as an example.Can have many states such as Play,Pause,Stop and Restart etc.

Implementation:

/**
 * @author Abhinaw.Tripathi
 *
 */
interface State
{
  public void pressPlay(MusicPlayerContextInterface context);
}

class StandbyState implements State
{

@Override
public void pressPlay(MusicPlayerContextInterface context)
{
 context.setState(new PlayingState());
}

}

class PlayingState implements State
{

@Override
public void pressPlay(MusicPlayerContextInterface context) {
// TODO Auto-generated method stub
context.setState(new StandbyState());
}

}

interface MusicPlayerContextInterface
{
  // public State state;
  public void requestPlay();
  public void setState(State state);
  public State getState();
}


class MusicPlayerContext implements MusicPlayerContextInterface
{
   State state;

   public MusicPlayerContext(State state)
   {
  this.state=state;
   }
 
@Override
public void requestPlay() {
// TODO Auto-generated method stub
state.pressPlay(this);
}

@Override
public void setState(State state) {
// TODO Auto-generated method stub
this.state=state;
}

@Override
public State getState() {
// TODO Auto-generated method stub
return state;
}

}

public class StatePatternTest {

/**
* @param args
*/
public static void main(String[] args)
{

MusicPlayerContext musicPalyer=new MusicPlayerContext(new StandbyState());
musicPalyer.requestPlay();
musicPalyer.setState(new PlayingState());
musicPalyer.requestPlay();
}


}

Advantages of State Design Pattern:

  • State patterns provides a clear state representation of an Object.
  • It allows a clear way for an object change its type at runtime.


Design Pattern - Observer Pattern tutorial example java

What is Observer Pattern?

Yes, Observer Pattern is Behavioral Design Pattern.In the Observer pattern ,an object called subject maintains a collect of objects called Observers. when the subject changes it notifies the observers.

For Example:
The observer pattern defines a link between objects so that when one objects state changes all dependent objects are updated automatically.a very famous example of Producer-Consumer problem in core java.

So, Observer pattern is designed to help cope with one to many relationships between objects allowing changes in an object to update many associated objects.


When to use Observer Pattern:

  • when a change to one object requires changing others and we do not know how many objects need to be changed.
  • When an object should be able to notify other objects without making assumptions about who these objects are.
  • when an abstraction has two aspects  one depends on the other.
Implementation:


public interface TempratureSubject
{
  public void addObserver(TempratureObserver TempratureObserver);
  public void removeObserver(TempratureObserver TempratureObserver);
  public void notify();
}

public interface TempratureObserver 
{
  public void update(int temparature);
}

public class TemparatureStation implements TempratureSubject
{
  Set<TempratureObserver> temparatureObservers;
  int temparature;
  
  public TemparatureStation(int temp)
  {
    this.temparature=temp;
  }
  
  public void addObserver(TempratureObserver tempObserver)
  {
    temparatureObservers.add(tempObserver);
  }
  
  public void removeObserver(TempratureObserver tempObserver)
  {
    temparatureObservers.add(tempObserver);
  }
  
  public void notify()
  {
    Iterator<TempratureObserver> it=tempObserver.iterator();
while(it.hasNext)
{
  TempratureObserver tempObserver= it.next();
  tempObserver.update(temparature);
}
  }
  
  public void setTemparature(int newTemparature)
  {
     System.out.println("Setting temparature to " + newTemparature); 
     temparature=newTemparature;
notify();
           
  }  
}



how client will use this pattern?Let say,

public class TempratureCustmer implements TempratureObserver
{
  public void update(int temparature)
  {
    System.out.println("Customer 1 found the temparature as"+ temparature);
  }
}

public class observerTest
{
  public static void main(String args[])
  {
    TemparatureStation tempStation=new  TemparatureStation();
TempratureCustmer tcustomer=new TempratureCustmer();
tempStation.addObserver(tcustomer);
tempStation.removeObserver(tcustomer);
tempStation.setTemparature(35);
  }
}

Very Important Points to remember before using Observer pattern

  • Also known as Depedents ,Publish-Subscibe patterns.
  • Define one to many dependency between objects.
  • Abstract coupling between subject and obsever.
  • Unexpected updates because observer have no knowledge of each others presence. 

Thursday, May 26, 2016

Structural Design Pattern tutorial example java

What is Structural Design Pattern?

Ans: 

Structural DP,s are used for structuring code and objects.It also can be described as how objects and classes can be combined to form larger structures.
Structural design patterns are used to organize our program into groups.

Categories of Structural Design Patterns


  • Object-Structural Design Pattern- It deals with how objects can be associated and composed to form larger and more complex structures.
  • Class-Structural Design Pattern - It deals with with abstraction using inheritance and provide more useful program interface.
Structural Design Patterns:
  • Adapter Pattern( is Class Structural Pattern only and rest all object.)
  • Bridge Pattern
  • Composite Pattern
  • Decorator Pattern
  • Facade Pattern
  • Flyweight Pattern
  • Proxy Pattern