Wednesday, July 8, 2015

TreeMap: Explicitly overriding equals along with the Comparable Interface

package com.collections;


import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

public class TreeMapHashCodeSample {
public static void main(String args[]) {
Employee1 emp1 = new Employee1("first", 120);
// Employee1 emp2 = new Employee1("firs11t", 120);
Employee1 emp2 = emp1;
TreeMap<String,Employee1> mp = new TreeMap<String,Employee1>();
mp.put("akkhil",emp1);
mp.put("gupta",emp2);
System.out.println("  Are  employees equal :  "
+ mp.get("akkhil").equals(mp.get("gupta")));
}
}



class Employee1 implements Comparable<Employee1>{
String name;
int score;
public Employee1(String name, int score) {
this.name = name;
this.score = score;
}
public boolean equals(Object o) {
return this.name == ((Employee1) o).name;
}
/*public int hashCode() {
return score;
}*/


/*public int compareTo(Employee1 o) {
 if(equals(o))
 return 1;
 return 0;
}*/


public int compareTo(Employee1 o) {
return  o.score - this.score;
}



}


HashCode Equals Contract in HashMap

package com.collections;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

class Employee {
String name;
int score;

public Employee(String name, int score) {
this.name = name;
this.score = score;
}
public boolean equals(Object o) {
return this.score == ((Employee) o).score;
}
public int hashCode() {
return score;
}
}

public class EqualsHashCodeExample {
public static void main(String args[]) {
Employee emp1 = new Employee("first", 120);
Employee emp2 = new Employee("Sec", 120);
Map<Employee, String> mp = new HashMap<Employee, String>();
mp.put(emp1, "akkhil");
mp.put(emp2, "gupta");
for (Map.Entry<Employee, String> m : mp.entrySet()) {
System.out.println("  fetch employee "
+ mp.get(emp1).equals(mp.get(emp2)));
}

}

}

Monday, July 6, 2015

Concurreny in Java

Concurreny in Java:
StateLess:
Lazily Initialization / Loading??
Atomicity: ( that􀀃a􀀃group􀀃of􀀃statements􀀃appear􀀃to􀀃execute􀀃as􀀃a􀀃single,􀀃indivisible )State Consistency can be maintained by updating the relates state variables in an atomic operation.
RaceCondition: Lazy Initialization
java.util.concurrent.atomic package AtomicLong, threadSafe?? How Atommic Long works
Instrinsic Lock/Monitor Lock( act as Mutex ):(Reference to an Object serves as the lock) .Every java object can act as implicit Lock.Oreder for which Threads to acquire lock first Not Gauranteed by using intrinsic Lock,( as we use notify() Or notifyAll() ) hence  Extrinsic Lock is to be used.
Intrinsic Locks are also ReEntrant: The Lock which is already held can be held again .
Synchronized blocks in Java are reentrant. This means, that if a Java thread enters a synchronized block of code, and thereby take the lock on the monitor object the block is synchronized on, the thread can enter other Java code blocks synchronized on the same monitor object
Example of ReEntrant Lock: 
package text.reentrant;

import java.util.concurrent.Semaphore;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ReEntrantSample {

public static void main(String args[]) {
Sharedresource sharedresource = new Sharedresource();
Thread t1 = new Thread(sharedresource, "1");
Thread t2 = new Thread(sharedresource, "2");
t1.start();
t2.start();
t1.run();
t2.run();
}

}


class Sharedresource implements Runnable {

CommonResources cr = new CommonResources();

public void run() {

cr.anotherMethod();
}
}

class CommonResources {

private final Lock lock = new ReentrantLock();

public synchronized void getCount() {

try {
for (int i = 0; i < 5; i++) {
System.out.println("Thread--"
+ Thread.currentThread().getName() + " i is " + i);

}


} finally {

}
}

public synchronized void anotherMethod() {

System.out.println(" Inside another method ............. ");
getCount();
}


}

Extrinsic Lock: Lock lock  = new ReEntrantLock(true) where true stands for fairness policy
and also deadlock situation can be avoided by using tryLock() of Lock class
Private Lock: Encapsulates the lock??? Advantages
Client Side Locking??????????
ReEntrant Lock Vs synchronized Difference:
1. fairness
2. tryLock()// using timeOut
3. determine the list of threads waiting.
EXAMPLE??
public class Widget {
public synchronized void doSomething() {
...
}
}
public class LoggingWidget extends Widget {
public synchronized void doSomething() {
System.out.println(toString() + ": calling doSomething");
super.doSomething();
}
}


Don't use lock to hold operations as I/O))???
Synchronization: Also determines NOT only mutual exclusion BUT also memory visibility(most updated value from shared memory) Hence reading/writing of threads to be on common Lock.
Volatile defines that the variable is shared among the Threads?? WHEN to USE???
Volatile gaurantees visibility but NOT atomicity
Avoid escapes: Don't use setters
class UnsafeStates {
private String[] states = new String[] {
"AK", "AL" ...
};
public String[] getStates() { return states; }
}


this reference escape during Construction????

Stack Confinemant: local variable are confined to stack

private to visibility is what final to immutuable


Volatile Refernce to Immutable Object Example???

final Objects are Immutable BUT final fields refering to Immutable Objects are NOT thread Safe

Objetcs defined using static initializer are threadSafe?????????How??
class CommonResources {
private final Lock lock = new ReentrantLock(true);
static int i;
static{
i = 0;
}

public  void getCount() {
//synchronized(CommonResources.class){
lock.lock();
try {
for (; i < 2; i++) {
System.out.println("Thread--"
+ Thread.currentThread().getName() + " i is " + i);
}
} finally {
lock.unlock();
}
//}
}


}

Read Only objects are threadSafe


Java Monitor Pattern: each class has its own intrinsic lock

Vector and problem with Collections.synchronizedSet()????

Iterators are failfast as:
1. starvation
2. DeadLock
3.Scalability as lock being hold for long time and hence CPU usage is more

Solution: clone since it is thread confined.

Collections.synchonizedMap(provide exclusive access/Lock to entire HashMap) ConcurrentHashMap( weakly consistent though NOT fail fast)

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

public class ConcurrentHashMapSample {
public static void main(String args[]) {
ConcurrentHashMap<String, String> hashMap = new ConcurrentHashMap<String, String>();
// Map<String,String> hashMap = new HashMap<String,String>();
// Collections.synchronizedMap(hashMap);
hashMap.put("core", "java");
hashMap.put("advanced", "J2ee");

for (Map.Entry<String, String> at : hashMap.entrySet()) {
hashMap.put(" newTopic ", "Sample");
System.out.println("  " + at.getKey() + "   " + at.getValue());
}

}
}

Collections.synchronizedMap(hashMap) will lock the whole Map and other threads can't access at same time and also the map can't be modified while iteration is going on, though has advantage against ConcurrentHashMap in terms of Consistency, i.e. to keep the data updated for all threads.


Similarly,
Collections.synchonizedList === CopyOnWriteArrayList

import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;

public class CopyOnWriteSample {
public static void main(String args[]) {
        CopyOnWriteArrayList<String> threadSafeList = new CopyOnWriteArrayList<String>();
//ArrayList<String> threadSafeList = new ArrayList<String>();
        threadSafeList.add("Java");
        threadSafeList.add("J2EE");
        threadSafeList.add("Collection");
        //add, remove operator is not supported by CopyOnWriteArrayList iterator
        Iterator<String> failSafeIterator = threadSafeList.iterator();
        while(failSafeIterator.hasNext()){
        //threadSafeList.add("Sample");
            System.out.printf("Read from CopyOnWriteArrayList : %s %n", failSafeIterator.next());
         failSafeIterator.remove(); //not supported in CopyOnWriteArrayList in Java
        }
    }
}


BlockingQueue Vs Producer - Consumer pattern??

Synchronizers:
1. Latches
2. Future Tasks
3. Semaphores
4. Barriers

DisAdvantages of Unbounded ThreadCreation

ThreadPools: Types of ThreadPools: Cached, Single,FixedThreadPool

LifeCycle Methods of ExecutorService: 
running,􀀃 shutting􀀃 down,􀀃 and􀀃 terminated.


Result Bearing Taks: Callable and FutureTasks

Real TIme Example???
Interupption policies and Cancellation via future

Newtaskfor􀀃????

ExecutorService􀀃: ShutDown options:
   --- shutDown
   ---shutDownNow


PoisonPills:
https://dzone.com/articles/producers-and-consumers-part-3

ShutDown Hooks : To shutdown JVM


DeadLock in ThreadPool


Ahmdals Law??








Graph : Creation of UnWeighted Graph using Matric Representation

package com.graph;

class Graph {
int[][] graphMatrix;
Vertex[] vertArray;
int vertCount;
int size;

Graph() {
size = 5;
vertArray = new Vertex[size];
graphMatrix = new int[size][size];
vertCount = 0;
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
graphMatrix[i][j] = 0;
}

void addVertex(char ch) {
addVertex(ch, vertArray);
}

void addVertex(char ch, Vertex[] vertArray) {
Vertex vert = new Vertex(ch);
// vertArray = new Vertex[size+3];
vertArray[vertCount++] = vert;
}

void addEdge(int src, int dest) {
graphMatrix[src][dest] = 1;
}

void displayGraph() {
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
if (graphMatrix[i][j] == 1)
System.out.println(" " + graphMatrix[i][j] + " "
+ vertArray[i].label + " " + vertArray[j].label);
}

}

class Vertex {
char label;

Vertex(char label) {
this.label = label;
}
}

class Edge {
char src;
char dest;

Edge(char src, char dest) {
this.src = src;
this.dest = dest;
}

}

public class GraphSample {
public static void main(String args[]) {
Graph graph = new Graph();

graph.addVertex('A');
graph.addVertex('B');
graph.addVertex('C');
graph.addVertex('D');
graph.addVertex('E');

graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 3);
graph.addEdge(1, 4);

graph.displayGraph();

}

}

Saturday, July 4, 2015

Threaded Binary Tree: An alternative to find the successor and predecessor in linear time


Threaded Binary Tree


package ds.threadedTree;

class ThreadedNode {

int tData;
ThreadedNode left, right;
boolean leftThread, rightThread;

public ThreadedNode() {

}

public ThreadedNode(int tData, ThreadedNode left, ThreadedNode right,
boolean leftThread, boolean rightThread) {
this.tData = tData;
this.left = left;
this.right = right;
this.leftThread = leftThread;
this.rightThread = rightThread;
}

public ThreadedNode(boolean leftThread, boolean rightThread) {
this.tData = Integer.MAX_VALUE;
this.left = this;
this.right = this;
this.leftThread = leftThread;
this.rightThread = rightThread;
}

}

class ThreadedBSTree {
private ThreadedNode root;

public ThreadedBSTree() {
root = new ThreadedNode(true, false);
}

/*
* public int insert(int tData){ ThreadedNode newNode = findNode(root,
* tData); // if(newNode==null)
*
* }
*/

public ThreadedNode findNode(ThreadedNode current, int tData) {
if (current.tData < tData) {
if (current.rightThread)
return current;
return findNode(current.right, tData);
} else if (current.tData > tData) {
if (current.leftThread)
return current;
return findNode(current.left, tData);
} else
return null;
}

public void insert(int ele) {
ThreadedNode ptr = findNode(root, ele);

/** element already present **/
if (ptr == null)
return;

if (ptr.tData < ele) {
ThreadedNode nptr = new ThreadedNode(ele, ptr, ptr.right, true,
true);
ptr.right = nptr;
ptr.rightThread = false;
} else {
ThreadedNode nptr = new ThreadedNode(ele, ptr.left, ptr, true, true);
ptr.left = nptr;
ptr.leftThread = false;
}
}

public void inOrder() {
ThreadedNode temp = root;
for (;;) {
temp = insucc(temp);
if (temp == root)
break;
System.out.print(temp.tData + " ");
}
}

public ThreadedNode insucc(ThreadedNode tree) {
ThreadedNode temp;
temp = tree.right;
if (!tree.rightThread)
while (!temp.leftThread)
temp = temp.left;
return temp;
}

}

public class ThreadedTree {

public static void main(String args[]) {

ThreadedBSTree threadedBSTree = new ThreadedBSTree();

threadedBSTree.insert(12);
threadedBSTree.insert(9);
threadedBSTree.insert(22);
threadedBSTree.insert(16);
threadedBSTree.insert(32);
threadedBSTree.insert(30);
threadedBSTree.insert(42);

threadedBSTree.inOrder();

}

}

Friday, July 3, 2015

Binary Tree

To print binary Tree Spirally and Inwards:

/*
   http://www.careercup.com/question?id=5749172554694656
*/
public void printSpiralInwards(Node root){
Map<Integer,ArrayList<Node>> mp = new HashMap<Integer, ArrayList<Node>>();
ArrayList<Node> arrayList = null;
ArrayList<Node> arrayList1 = null;
int i = 0;
if(root == null)
return;
Deque<Node> queue = new LinkedList<Node>();
queue.add(root);
queue.add(null);
while(queue.size()>1){
  Node temp = queue.peekFirst();
  
  arrayList = new ArrayList<Node>();
  while(temp!=null){
 
 temp = queue.pollFirst();
 arrayList.add(temp);
 System.out.println(" "+ temp.data );
  
   if(temp.left!=null)
  queue.offerLast(temp.left);
 if(temp.right!=null)  
 queue.offerLast(temp.right);
 temp = queue.peekFirst();
  }
  mp.put(i++, arrayList);
  temp = queue.peekLast();
  arrayList1 = new ArrayList<Node>();
  while(temp!=null){
 temp = queue.pollLast();
 arrayList1.add(temp);
 System.out.println(" "+ temp.data );
 if(temp.right!=null)
  queue.offerFirst(temp.right);
 if(temp.left!=null)  
 queue.offerFirst(temp.left);
 temp = queue.peekLast();
  }
  mp.put(i++, arrayList1);
}
    
  Deque<ArrayList<Node>> de = new LinkedList<ArrayList<Node>>();
  de.addAll(mp.values());

  while(!de.isEmpty()){
  System.out.println(" ");
  ArrayList<Node> first = de.pollFirst();
  Iterator<Node> itr = first.iterator();
  while(itr.hasNext()){
  System.out.print(" "+itr.next().data);
  }
  
  System.out.println(" ");
  ArrayList<Node> sec = de.pollLast();
  Iterator<Node> itr1 = sec.iterator();
  while(itr1.hasNext()){
  System.out.print(" "+itr1.next().data);
  }
  
  
  
  }
  
  
}



Find Maximum in a Binary Tree(NOT BST)

int findMax(Node node) {
int max = Integer.MIN_VALUE;
Queue<Node> queue = new LinkedList<Node>();
queue.add(node);
if (root == null)
return 0;
else {
while (!queue.isEmpty()) {
Node temp = queue.poll();
if (max < temp.tData)
max = temp.tData;
if (temp.lefNode != null)
queue.add(temp.lefNode);
if (temp.rightNode != null)
queue.add(temp.rightNode);
}
return max;
}
}




Generate the Mirror of a Binary Tree:

public void getMirrorOfTree(Node1 node) { Node1 temp; if (node != null) { getMirrorOfTree(node.lefNode1); getMirrorOfTree(node.rightNode1); temp = node.lefNode1; node.lefNode1 = node.rightNode1; node.rightNode1 = temp; } }

To Find Ancestors of a Node:

public boolean ancestorsOfNode(Node1 node, int nData) { if (node == null) return false; if (node.tData == nData) return true; if (ancestorsOfNode(node.lefNode1, nData) || ancestorsOfNode(node.rightNode1, nData)) { System.out.println(" -- " + node.tData); return true; } return false; }

Binary Search Tree(BST)

Adding Node to Tree:

public void buildTree(int tData) {
Node1 newNode1 = new Node1(tData);
if (root == null)
root = newNode1;
else {
Node1 current = root;
Node1 parent;
while (true) {
parent = current;
if (tData < current.tData)// go left
{
current = current.lefNode1;
if (current == null) {
parent.lefNode1 = newNode1;
return;
}
} else {
current = current.rightNode1;
if (current == null) {
parent.rightNode1 = newNode1;
return;
}
}
}
}
}


Check if Node is present in Node:

boolean isPresent(int tData){
if(root==null)
System.out.println(" error ");
else{
Node1 current = root;
while(current!=null && current.tData  != tData){
if(current.tData > tData)
current = current.lefNode1;
else if(current.tData < tData)
    current = current.rightNode1;
}
if(current!=null)return true;
}
return false;
}

Find Maimum Element in BST( with Recursion):

public int findMaxBT(Node1 node) {
Node1 current = node;
while (current.rightNode1 != null) {
current = current.rightNode1;
}
return current.tData;
}



Queue Implementation as LinkedList

package ds.queue.implementation;

class QueueList {
Node first = null;

public QueueList(Node first) {
this.first = first;
}

QueueList() {

}

void enQueue(int sData) {
Node newNode = new Node(sData);
if (first == null)
first = newNode;
else {
Node current = first;
while (current.next != null) {
current = current.next;
// newNode.next = null;
}
current.next = newNode;
newNode.next = null;
}
}

boolean isEmpty() {
return first == null;
}

void dequeue() {
if (isEmpty())
return;
else {
first = first.next;
}
}

void display(Node node) {
Node current = node;
do {
System.out.print(" " + current.nData);
current = current.next;
} while (current != null);
}
}

class Node {
int nData;
Node next;

Node(int nData) {
this.nData = nData;
}

Node() {
}
}

public class QueueSample {
public static void main(String args[]) {
QueueList queueList = new QueueList();
queueList.enQueue(111);
queueList.enQueue(222);
queueList.enQueue(333);
queueList.enQueue(444);
queueList.display(queueList.first);
queueList.dequeue();
System.out.println();
queueList.display(queueList.first);

}

}

Stack Implementation as Array , Dynamic Array and LinkedList

Stack implementation as Array:

package ds.stack.implementation;

class StackArray {

static int stackSize = 3;

int[] stackArray = new int[stackSize];

int index = -1;

void add(int sData) {
if (index < stackSize - 1) {
stackArray[++index] = sData;
} else {
System.out.println(" Stack OverFlow");
}
}

void remove() {
if (index >= 0)
index--;
else
System.out.println(" Stack UnderFlow");

}

void display() {
for (int n = 0; n < index; n++)
System.out.print(" " + stackArray[n]);
}

}

public class StackAsArrayImpl {
public static void main(String args[]) {
StackArray stackArray = new StackArray();
stackArray.add(11);
stackArray.add(12);
stackArray.add(13);
stackArray.display();
stackArray.remove();
System.out.println("  -------------------------------------- ");
stackArray.display();
}
}


Stack Implementation as LinkedList:


package ds.stack.implementation;

class StackList {
Node first = null;

public StackList(Node first) {
this.first = first;
}

StackList() {

}

void push(int sData) {
Node newNode = new Node(sData);
if (first == null)
first = newNode;
else {
Node current = first;
while (current.next != null) {
current = current.next;
// newNode.next = null;
}
current.next = newNode;
newNode.next = null;
}
}

void pop() {
if (first == null)
return;
else {
Node current = first.next;
while (current.next.next != null) {
current = current.next;
}
current.next = null;
}
}

void display(Node node) {
Node current = node;
do {
System.out.print(" " + current.nData);
current = current.next;
} while (current != null);
}
}

class Node {
int nData;
Node next;

Node(int nData) {
this.nData = nData;
}

Node() {
}
}

public class StackAsListSample {
public static void main(String args[]) {
StackList stackList = new StackList();

stackList.push(12);
stackList.push(13);
stackList.push(14);
stackList.push(15);
stackList.push(16);

stackList.display(stackList.first);

stackList.pop();
System.out.println();
System.out.println(" -------------------------- ");

stackList.display(stackList.first);

}

}


CircularLinkedList

Add Node at End:

public void addNode(int nData) {
Node newNode;
newNode = new Node(nData);
if (first == null) {
first = newNode;
} else {
Node current = first;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}

Add Node at particular Index:

    public void addNodeAt(int nData,int index){
    Node newNode = new Node(nData);
    Node current = first;
    int count = 0;
    while (current!=null && count!=index) {
    current = current.next;
    count++;
}

    newNode.next = current.next;
    current.next = newNode;
    }

Thursday, July 2, 2015

DoublyLinkedList

Add Node at front:

public void addNodeFront(DoublyLinkedList doublyLinkedList, int nData) {
Node newNode = new Node(nData);
Node current = doublyLinkedList.first;
if (first == null)
first = newNode;
else {
first.previous = newNode;
newNode.next = first;
first = newNode;
}
}



Add Node at end:

public void addNode(int nData) {
Node newNode = new Node(nData);
Node current = first;
if (first == null)
first = newNode;
else {
while (current.next != null) {
current = current.next;
}
current.next = newNode;
newNode.next = null;
newNode.previous = current;
}
}



Delete Node at specific Index:

   public Node deleteItem(int data){
  Node current = first;
  while (current.nData!=data) {
  current = current.next;
}
  if(current.next!=null){
  current.next.previous = current.previous;
  current.previous.next = current.next;
  }
  else
current.previous.next = null;
  return current;
   }


SinglyLinkedList

Adding Node at front:

Node first = null;
   //Node start = null;
public void addNode(int nData){
Node newNode = new Node((int)nData);
if(first==null){
first = newNode;
}else{
   newNode.next = first;
   first = newNode;

Add Node at Last:

Node current = first; while (current.next != null) {
 current = current.next; } current.next = newNode;

Add Node at an index


public void addNodeAt(int nData,int index){ //if(check for list length) Node newNode = new Node(nData); Node current = first; int count = 0; while (current!=null && count!=index) { current = current.next; count++; } newNode.next = current.next; current.next = newNode; }


Delete Node at Last:

Node current = first; Node forward = first.next; if (first == null) return; else { while (forward.next != null) { current = current.next; forward = forward.next; } current.next = null; }


Delete Node at particular Index:

public Node delNode(int nData) { Node previous = first; Node current = first.next; while (current.nData != nData) { current = current.next; previous = previous.next; } if (current.next == null) previous.next = null; previous.next = current.next; return current; }


Delete LinkedList

public void deleteList(){ first = null; }



Counting Sort


Sorting Algorithms

Sorting Algorithms:

  Binary Sort:

   BubbleSort:

 package com.algorithm.sorting;

public class BubbleSortSample {
static void bubbleSort(int[] in) {
int temp;
int n = in.length;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if (in[j] < in[i]) {
temp = in[i];
in[i] = in[j];
in[j] = temp;
}
}
}

System.out.println(" After sorting ");
for (int i : in) {
System.out.print(" " + i);
}

}

public static void main(String args[]) {

int[] in = { 12, 2, 34, 5, 44, 12, 4, 7 };
for (int i : in) {
System.out.print(" " + i);
}

bubbleSort(in);

}

}

  SelectionSort:

 package com.algorithm.sorting;


public class SelectionSortSample {

static void doSelectionSort(int[] in) {

int temp;

int min = 0;

for (int i = 0; i < in.length - 1; i++) {

in[min] = in[i];

for (int j = i + 1; j < in.length; j++) {

if (in[j] < in[min]) {

min = j;

}

}

temp = in[i];

in[i] = in[min];

in[min] = temp;

}

}


public static void main(String args[]) {

int[] in = { 12, 2, 34, 5, 44, 12, 4, 7 };

for (int i : in) {

System.out.print(" " + i);

}

doSelectionSort(in);

System.out.println("  After Sorting");

for (int i : in) {

System.out.print(" " + i);

}

}

}



  InsertionSort:
  MergeSort:
  ShellSort:
  HeapSort:


 Non-Comparison Sort:
    Counting Sort
     Radix Sort
     Bucket Sort
     Topological Sort:

Wednesday, July 1, 2015

Design Patterns

Design Patterns:
  Classified as :

Creational Pattern  :

                                 Singleton DesignPattern


package test.creational.designPattern;



class DatabaseConnection{
private static DatabaseConnection instance = new DatabaseConnection();
private DatabaseConnection(){

}
public static DatabaseConnection getDBConnection(){
return instance;
}
public void getConnection(){
System.out.println(" Established to Database successfully ");
}
}


public class SingletonExample {
public static void main(String args[]) {
DatabaseConnection.getDBConnection().getConnection();
}

}

                                 Factory Design Pattern

package test.creational.designPattern;

interface Shape {
void getShape();
}

class Circle implements Shape {

@Override
public void getShape() {
System.out.println(" Inside Circle ");

}

}

class Rectangle implements Shape {

@Override
public void getShape() {
System.out.println(" Inside Rectangle ");

}

}

class Square implements Shape {

@Override
public void getShape() {
System.out.println(" Inside Square ");

}
}

class Shapefactory {
public Shape getType(String shape) {
if (shape.equals("circle")) {
return new Circle();
}
if (shape.equals("rect")) {
return new Rectangle();
}
if (shape.equals("square")) {
return new Square();
}
return null;

}
}

public class FactoryExample {
public static void main(String args[]) {

Shapefactory shapefactory = new Shapefactory();

Shape shape1 = shapefactory.getType("rect");

shape1.getShape();

}
}

                                 Abstract Factory Pattern
                                     
Structural Patterns :

                                          Adapter:

package test.creational.designPattern;

interface MediaPlayer {

public void play(String audioType, String filename);
}

class MediaAdapter implements MediaPlayer {

AdvancedMediaPlayer advancedMusicPlayer;

public MediaAdapter(String audioType) {

if (audioType.equalsIgnoreCase("vlc")) {
advancedMusicPlayer = new VlcPlayer();

} else if (audioType.equalsIgnoreCase("mp4")) {
advancedMusicPlayer = new Mp4Player();
}

}

public void play(String audioType, String fileName) {

if (audioType.equalsIgnoreCase("vlc")) {
advancedMusicPlayer.playVlc(fileName);
} else if (audioType.equalsIgnoreCase("mp4")) {
advancedMusicPlayer.playMp4(fileName);
}
}

}

class AudioPlayer implements MediaPlayer {
MediaAdapter mediaAdapter;

@Override
public void play(String audioType, String fileName) {

// inbuilt support to play mp3 music files
if (audioType.equalsIgnoreCase("mp3")) {
System.out.println("Playing mp3 file. Name: " + fileName);
}

// mediaAdapter is providing support to play other file formats
else if (audioType.equalsIgnoreCase("vlc")
|| audioType.equalsIgnoreCase("mp4")) {
mediaAdapter = new MediaAdapter(audioType);
mediaAdapter.play(audioType, fileName);
}

else {
System.out.println("Invalid media. " + audioType
+ " format not supported");
}
}
}

interface AdvancedMediaPlayer {

public void playVlc(String fileName);

public void playMp4(String fileName);
}

class VlcPlayer implements AdvancedMediaPlayer {
@Override
public void playVlc(String fileName) {
System.out.println("Playing vlc file. Name: " + fileName);
}

@Override
public void playMp4(String fileName) {
// do nothing
}
}

class Mp4Player implements AdvancedMediaPlayer {

@Override
public void playVlc(String fileName) {
// do nothing
}

@Override
public void playMp4(String fileName) {
System.out.println("Playing mp4 file. Name: " + fileName);
}
}

public class AdapterSample {

public static void main(String[] args) {
AudioPlayer audioPlayer = new AudioPlayer();

audioPlayer.play("mp3", "beyond the horizon.mp3");
audioPlayer.play("mp4", "alone.mp4");
audioPlayer.play("vlc", "far far away.vlc");
audioPlayer.play("avi", "mind me.avi");
}

}

                         Proxy :
                                Protection , Remote
                         Bridge

                         Facade

package test.structural.designPattern;

interface Goods {

void getGoods();
}

class PackagedGoods implements Goods {
public void getGoods() {
System.out.println(" Allow to get the Packaged Foods");
}
}

class LooseGoods implements Goods {
public void getGoods() {
System.out.println(" Allow to get the Loose Food items");
}
}

class StoreOwner {
private Goods looseGoods;
private Goods packagedGoods;

public StoreOwner() {
this.looseGoods = new LooseGoods();
this.packagedGoods = new PackagedGoods();
}

public void getPackagedGoods() {
packagedGoods.getGoods();
}

public void getLooseGoods() {
looseGoods.getGoods();
}

}

public class FacadeSample {
public static void main(String[] args) {
StoreOwner storeOwner = new StoreOwner();
storeOwner.getPackagedGoods();
storeOwner.getLooseGoods();
}
}

                         FlyWeight

Behavioural Patterns

                         State

package test.behavioural.designPattern;

interface CompressionType {
void compressionType(CompressionContext context);
}

class ZipCompression implements CompressionType {
public void compressionType(CompressionContext context) {
System.out.println(" Compression Strategy is : ZIP");
}
}

class WinrarCompression implements CompressionType {
public void compressionType(CompressionContext context) {
System.out.println(" Compression Strategy is : WINRAR");
}
}

class CompressionContext {
CompressionType compressionType = new ZipCompression();

public void setCompressionType(CompressionType compressionType) {
this.compressionType = compressionType;
}

void getCompression() {
compressionType.compressionType(this);
}
}

public class StateDPDSample {

public static void main(String args[]) {

CompressionContext compressionContext = new CompressionContext();

compressionContext.getCompression();

compressionContext.setCompressionType(new WinrarCompression());

compressionContext.getCompression();

}

}

                         Strategy  

package test.behavioural.designPattern;
interface Country {
void currency();
}
class Asian implements Country {
@Override
public void currency() {
System.out.println(" Currncy is INR");
}
}
class European implements Country {
@Override
public void currency() {
System.out.println(" Currency is EURO");
}
}
class CountryContext {
Country country;
public void setCountry(Country country) {
this.country = country;
}
public void currency() {
country.currency();
}
}
public class StrategyDesignPattern {
public static void main(String args[]) {
CountryContext countryContext = new CountryContext();
countryContext.setCountry(new Asian());
countryContext.currency();
countryContext.setCountry(new European());
countryContext.currency();
}
}
  

                         Observer


package test.behavioural.designPattern;

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

class NasdaqStock {

private int stockPrice;
List<StockExchange> stockExchangeList = new ArrayList<StockExchange>();

public void setStockPrice(int stockPrice) {
this.stockPrice = stockPrice;
notifyOtherExchanges();
}

public int getStockPrice() {
return stockPrice;
}

void notifyOtherExchanges() {
for (StockExchange s : stockExchangeList) {
s.getStockValue();
}
}

public void attach(StockExchange stockExchange) {
stockExchangeList.add(stockExchange);
}

}

abstract class StockExchange {

NasdaqStock nasdaqStock;

abstract void getStockValue();
}

class NSE extends StockExchange {

NSE(NasdaqStock nasdaqStock) {
this.nasdaqStock = nasdaqStock;
this.nasdaqStock.attach(this);
}

@Override
void getStockValue() {
System.out.println(" Value  at NSE after change at Nasdaq is "
+ this.nasdaqStock.getStockPrice());

}

}

class BSE extends StockExchange {
BSE(NasdaqStock nasdaqStock) {
this.nasdaqStock = nasdaqStock;
this.nasdaqStock.attach(this);
}

@Override
void getStockValue() {
System.out.println(" Value at BSE after change at Nasdaq is "
+ this.nasdaqStock.getStockPrice());
}

}

public class ObserverPatternSample {
public static void main(String args[]) {

NasdaqStock nasdaqStock = new NasdaqStock();

new BSE(nasdaqStock);
new NSE(nasdaqStock);
nasdaqStock.setStockPrice(100);

nasdaqStock.setStockPrice(5000);

}
}

                         Chain of Responsibility