Categories
Uncategorized

Prototype Pattern

CREATIONAL PATTERN

Prototype pattern deals with encapsulating cloning process. As the name suggests, it is used to create prototypes by cloning, not real objects from scratch. This pattern can be used in situation where creating new object of class from scratch is costly operation, so instead it is cloned from existing objects. For example, for ome process need to prepare List of all account numbers associated with bank and customer are millions. In this case, it is costly to prepare such list object by reading through database, so such list is copied from existing list object.

Account.java

public class Account 
implements Cloneable{
	

	private String accountNo;
	private String mailId;
	private String firstName,lastName;
	
	public String getAccountNo() {
		return accountNo;
	}

	public void setAccountNo(String accountNo) {
		this.accountNo = accountNo;
	}

	public String getMailId() {
		return mailId;
	}

	public void setMailId(String mailId) {
		this.mailId = mailId;
	}

	public String getFirstName() {

		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public Account(String accountNo, String firstName, String lastName, String mailId) {
		// TODO Auto-generated constructor stub
		this.accountNo=accountNo;
		this.firstName = firstName;
		this.lastName = lastName;
		this.mailId = mailId;
	}

	
}

AccountHolderList.java

import java.io.File;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class AccountHolderList implements Cloneable{

	private ArrayList accounts;
	
	public ArrayList getAccountsList(){
		return accounts;
	}
	
	public AccountHolderList() {
		// TODO Auto-generated constructor stub
		accounts = new ArrayList();
	}

	public void loadListFromDatabase(){
		//load accounts data from xml based database
		
		try   
		{  
		//creating a constructor of file class and parsing an XML file  
		File file = new File("src/AccountsDatabase.xml");  
		//an instance of factory that gives a document builder  
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
		//an instance of builder to parse the specified xml file  
		DocumentBuilder db = dbf.newDocumentBuilder();  
		Document doc = db.parse(file);  
		doc.getDocumentElement().normalize();  
		System.out.println("Root element: " + doc.getDocumentElement().getNodeName());  
		NodeList nodeList = doc.getElementsByTagName("Account");  
		// nodeList is not iterable, so we are using for loop  
		for (int itr = 0; itr < nodeList.getLength(); itr++)   
		{  
		Node node = nodeList.item(itr);  
		System.out.println("\nNode Name :" + node.getNodeName());  
		if (node.getNodeType() == Node.ELEMENT_NODE)   
		{  
		Element eElement = (Element) node;
		String accountNo = eElement.getElementsByTagName("accountNo").item(0).getTextContent();
		String firstName = eElement.getElementsByTagName("firstname").item(0).getTextContent();
		String lastName  = eElement.getElementsByTagName("lastname").item(0).getTextContent();
		String mailId = eElement.getElementsByTagName("mailId").item(0).getTextContent();
		System.out.println("accountNo: "+ accountNo);  
		System.out.println("First Name: "+ firstName);  
		System.out.println("Last Name: "+ lastName);  
		System.out.println("mail Id: "+ mailId);  
		Account accountData = new Account(accountNo, firstName, lastName, mailId);
		accounts.add(accountData);
		}  
		}  
		}   
		catch (Exception e)   
		{  
		e.printStackTrace();  
		}  
		System.out.println("Loaded accounts from database ::"+accounts.size());
	}
	
	public Object clone() {
	      Object clone = null;
	      try {
	         clone = super.clone();
	      } catch (CloneNotSupportedException e) {
	         e.printStackTrace();
	      }
	      return clone;
	  }
}

PrototypePatternDemo.java

import java.util.ArrayList;
import java.util.Iterator;

public class PrototypePatternDemo {

	public static AccountHolderList accountHolderList;
	static{
		
		//load accounts from database at time of system initiliazation
		accountHolderList = new AccountHolderList();
		accountHolderList.loadListFromDatabase();
	}
	
	public PrototypePatternDemo() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		
		//clone accounts List for sending mail, instrad of reading from database
		AccountHolderList clonedList = (AccountHolderList)accountHolderList.clone();
		
		ArrayList accList =clonedList.getAccountsList(); 
		Iterator listItr = accList.iterator();
		
		Account acc;
		while(listItr.hasNext()){
			acc = (Account)listItr.next();
			System.out.println("wished Happy New year to ::" + acc.getMailId()); 
		}
		
	}

}

Output

Categories
Uncategorized

Builder Pattern

CREATIONAL PATTERN

As the name suggests, builder pattern is about encapsulating logic for building of complex composite object by composing small, simple objects. Sometimes, every real-world entity cannot be directly created as Class. For example Lunchset.

Item.java


public interface Item {

public String getName();
public String getCost();
	
}

Cola.java


public class Cola implements Item {

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

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return "Coca Cola";
	}

	@Override
	public String getCost() {
		// TODO Auto-generated method stub
		return "20 INR";
	}

}

Sprite.java


public class Sprite implements Item {

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

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return "Sprite";
	}

	@Override
	public String getCost() {
		// TODO Auto-generated method stub
		return "30 INR";
	}

}

ChickenBurger.java


public class ChickenBurger implements Item {

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

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return "Chicken Burger";
	}

	@Override
	public String getCost() {
		// TODO Auto-generated method stub
		return "50 INR";
	}

}

VegBurger.java


public class VegBurger implements Item {

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

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return "Veg Burger";
	}

	@Override
	public String getCost() {
		// TODO Auto-generated method stub
		return "40 INR";
	}

}

LunchSet.java

import java.util.ArrayList;
import java.util.Iterator;

public class LunchSet {

	ArrayList items ;
	
	public LunchSet() {
		// TODO Auto-generated constructor stub
		items  = new ArrayList();
	}

	public void printBills(){
		if(items==null)
		{
			System.out.println("Pls make order, set is empty");
		}
		
		Iterator itr = items.iterator();
		Item item;
		while(itr.hasNext()){
			item = (Item)itr.next();
			System.out.println(item.getName() + ", cost :" + item.getCost());
		}
	}

	public void addItem(Item item){
		items.add(item);
		return;
	}
}

BuilderPatternDemo.java


public class BuilderPatternDemo {

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

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

		//I want Chicken burger and Coke
		LunchSet set1 = new LunchSet();
		set1.addItem(new ChickenBurger());
		set1.addItem(new Cola());
		System.out.println("Here is your set, pls pay bills as below");
		set1.printBills();
		
		
		//I want Veg Burger and Sprite
		LunchSet set2 = new LunchSet();
		set2.addItem(new VegBurger());
		set2.addItem(new Sprite());
		System.out.println("Here is your set, pls pay bills as below");
		set2.printBills();
		
		
		
		
	}

}

Categories
Algorithms & Design Design Pattern

Singleton Pattern

CREATIONAL PATTERN

As its name suggests, singleton pattern is used to maintain single instance of certain class. There can be situations, when we want to create object of class only one time and keep using same object all the time. We will never want to create second object of same class. For example, There is only one sun in our solar system. Hence we cannot have several objects of class named Sun, but only one. In Banking system, each customer account has unique account number. Hence we would wish to design class AccountNumberGenerator. But we would use singleton only one instance of that class, who would take responsibility to generate unique account number for request generated multiple bankers of bank. If we create instances of this class, it may not guarantee uniqueness of account number. Please follow example below how to achieve it technically.

AccountNumberGenerator.java

public class AccountNumberGenerator {

	private static AccountNumberGenerator AccNoInstance = new AccountNumberGenerator();
	private int lastAccountNo;
	
	private AccountNumberGenerator() {
		// TODO Auto-generated constructor stub
		lastAccountNo=0;
	}
	
	public static AccountNumberGenerator getInstance(){
		if(AccNoInstance == null)
			AccNoInstance = new AccountNumberGenerator();
		return AccNoInstance;
	}

	public int getAccountNumber(){
		return (++this.lastAccountNo);
	}
}

Banker.java

public class Banker {

	private String name; 
	public Banker(String name) {
		// TODO Auto-generated constructor stub
		this.name = name;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	int providePassbook(){
		int accountNo;
		AccountNumberGenerator instance = AccountNumberGenerator.getInstance();
		accountNo = instance.getAccountNumber();
		return accountNo;
	}
}

SinglePatternDemo.java

public class SingletonPatternDemo {

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

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

		Banker sam = new Banker("Samuel");
		System.out.println("Hey Samuel,I want to open account with your branch");
		System.out.println(sam.getName()+" : Sure sir, we provide you passbook with account No :"+sam.providePassbook());
		
		Banker rajib = new Banker("Rajib");
		System.out.println("Hey rajib,I want to open account with your branch");
		System.out.println(rajib.getName()+" : Sure sir, we provide you passbook with account No :"+sam.providePassbook());
		
		
	}

}

Output

Categories
Uncategorized

Factory Pattern

CREATIONAL PATTERN.

Factory pattern deals with encapsulating logic for creation of objects. Suppose in banking system banker want to provide the passbook to new customer. In this case surely passbooks are not created in every branch of bank but manufacturing of passbooks would be carried out by factories & dispatched to branches on request. In this business model, all operations & logistics are managed by factories for passbooks production & branches are totally unaware or not interested to know how factory manage it. In this case if want to modify construction of object, we will have to change only factory class, not other classes like banker or customer

Passbook.java

public class Passbook {

	private String color;
	private int pageSize;
	
	public Passbook(String color, int pageSize) {
		// TODO Auto-generated constructor stub
		this.color = color;
		this.pageSize=pageSize;
	}

	public String getColor() {
		return color;
	}
	public int getPageSize() {
		return pageSize;
	}


}

PassbookFactory.java

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

public class PassbookFactory {
	
	private static Map colorCodeMap;
	private static Map sizeCodeMap;
	
	
	public PassbookFactory() {
		
		if(colorCodeMap==null){
			colorCodeMap = new HashMap();
			colorCodeMap.put(1,"Orange");
			colorCodeMap.put(2,"brown");
			colorCodeMap.put(3,"Gray");
			colorCodeMap.put(4,"Black");
			colorCodeMap.put(5,"White");
		}
		
		if(sizeCodeMap==null){
			sizeCodeMap = new HashMap();
			sizeCodeMap.put("small",50);
			sizeCodeMap.put("medium",100);
			sizeCodeMap.put("large",200);
		}
		
	}

	public Passbook createPassbook(int colorCode, String size){
		
		String requestedColor = colorCodeMap.containsKey(colorCode)?
                                        (String)colorCodeMap.get(colorCode):
                                         (String)colorCodeMap.get(5);
		int requestedPageSize = sizeCodeMap.containsKey(size)
                                        ?(int)sizeCodeMap.get(size)
                                        :(int)sizeCodeMap.get("small");
		Passbook pbook = new Passbook(requestedColor,requestedPageSize);
		
		return pbook;
		
	}
}

Banker.java

public class Banker {

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

}

FactoryPatternMain.java

import java.util.Scanner;

public class FactoryPatternMain {

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

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

		Scanner inputStream = new Scanner(System.in);
		
		PassbookFactory pbFactory = new PassbookFactory();
		
		System.out.println("enter color code (options : 1,2,3,4,5) :");
		int colorCode = inputStream.nextInt();
		System.out.println("enter passbook size (options : small, medium, large)");
		String passbookSize = inputStream.next().trim();
		
		Passbook passbookGranted = pbFactory.createPassbook(colorCode, passbookSize);
		
		System.out.println("You have been provided passbook which has color ::"+ passbookGranted.getColor()+", with pageSize::"+passbookGranted.getPageSize());
			
		
	}

}

Output

Categories
Design Pattern

What is Design Pattern

Software development is an art of programming. But we don’t always write code from scratch we often copy paste code blocks. For example once we learn how to read text from file, we will continue to apply same logic at point of time later. That means reusing our learning. But is development is also about designs. What if we want to sort numbers, surely we will think about algorithms like bubble sort, heap sort etc. That means we reuse already learned logical solutions to same problem.

Design pattern is also same thing, it is collection of logical solutions to day to day design problems. Factory pattern tells us how to design construction of objects, iterator pattern tells us how to design iterator for iterations etc. Just like algorithms are aimed at minimizing complexity of solutions. Design patterns are aimed at following

  1. Reusability of code – same class or method to be used at multiple places.
  2. Minimum exposure of code to changes. – If we put creation logic in factory class, we will modify factory class only for creation class. No need to touch code where iteration logic is written.

Design patterns are classified into following categories

  1. Creational patterns
  2. Structural patterns
  3. Behavioral patterns

Categories
Tech Intuitions

HighCharts

Real Word analytics cannot be based on only numbers or digits. That is why may be MS Excel emerged as excellent tool for data representations in variety of charts & graphs, as desktop software. There are also several widget frameworks being developed for Web, for e.g. Ext JS Gantt, HighCharts, kavaChart etc. However Highcharts is emerging as simple, comprehensive charting tools for web Applications.

HighChart is licensed javascript based charting framework. It provides variety of chart & graphs, based on inputs in JSON format. As it is purely based on Javascript, there is no need to have additional browser plugins.

It provides ample documentation with comprehensive demo applications. Javascript APIs are simple to use & easy to understand, find in documentation. Input for charts passed using JSON based syntax. In addition to simple charting, graphs drawing it also provides zooming behaviors in different senses for e.g. zooming in from month to week to day. Also charts,graphs can be manipulated dynamically. High charts are highly configurable for representations. Following are some distinct features

  1. Multiple browser support, also support touch devices
  2. Some features are free
  3. Lightweight, highly configurable, dynamic
  4. Advanced features – Export, print, zooming in data
  5. Comprehensive coverage of charts, graphs.
  6. Ease of API & configuration

visit the site for demo

Categories
Tech Intuitions

websocket

In 21st Century, Internet has become supreme technology for its impact on lives by providing increasingly virtual connectivity for various possible kind of information & many more to come. Perhaps internet has increasingly misinterpreted as synonym for world wide web, thanks to strong emergence of eCommerce, & virtual collaborative public platforms. WWW has brought markets, hotels, theaters, acquaintances at your clicks.

Perhaps Http is one of the application protocols that drives the backstage for WWW. Hypertext Transfer protocol has always served the requested information. But requesting information not an only phenomenon that humans will love. We would want feeds, updates, notifications, messages; not on request but based on circumstances. Servers should send important feeds to clients.

This is where websocket comes into picture, to provide duplex communication between client & servers, unlike traditional http model based on request-response paradigm. websocket standardized by IEFT as RFC 6455 in 2011. It is added in 7th layer in OSI model & 4th layer in TCP/IP model, as another application layer protocol.

Most of web browsers started supporting websocket, including mozilla firefox, safari, chrome, IE.

Most of Application servers started supporting websocket.

Some of popular frameworks which I come across, offering websocket based APIs – J2EE, Spring, Atmosphere.

Categories
Tech Intuitions

Vue.js

Vue.js is lightweight open source Model-view-viewmodel based javascript framework. Its developed with focus mainly on view layer to create simple responsive web applications.

With Vue.js data elements can be bound to HTML components. Binding can be two ways i.e. changes in data element can be reflected in HTML component & HTML component changes can get reflected to data element. Vue.js provides rich set of javascript APIs ,directives around two-way data binding & ease of content development.

Categories
About Me

First Attempt

Powered by passion,

Driven by zeal.

Hello Everybody,

This is first time I am trying hands over blog write ups.

I am a Computer Engineer by profession, and always fascinated by software advancements across different digital directions. Idea here is to put intuitive information about latest tech advances. I am an enthusiast learner for technologies & loves to spread the articulations.

Stay tuned & Subscribe below to get notified when I post new updates.

— Amol Dake
Design a site like this with WordPress.com
Get started