Design Patterns in java
Design Patterns in java
File: EmployeeRecord.java
class EmployeeRecord implements Prototype
{
private int id;
private String name, designation;
private double salary;
private String address;
public EmployeeRecord()
{
System.out.println(" Employee Records
of Oracle Corporation ");
System.out.println("---------------------------------------------");
System.out.println("Eid"+"\
t"+"Ename"+"\t"+"Edesignation"+"\t"+"Esalary"+"\t\
t"+"Eaddress");
}
@Override
public Prototype getClone()
{
return new
EmployeeRecord(id,name,designation,salary,address);
}
}
File: PrototypeDemo.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class PrototypeDemo
{
public static void main(String[] args) throws
IOException
{
BufferedReader br =new
BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Employee Id: ");
int eid=Integer.parseInt(br.readLine());
System.out.print("\n");
System.out.print("Enter Employee
Address: ");
String eaddress=br.readLine();
System.out.print("\n");
EmployeeRecord e1=new
EmployeeRecord(eid,ename,edesignation,esalary,eaddr
ess);
e1.showRecord();
System.out.println("\n");
EmployeeRecord e2=(EmployeeRecord)
e1.getClone();
e2.showRecord();
}
}
Builder Design Pattern
Builder Pattern says that "construct a complex object
from simple objects using step-by-step approach"
It is mostly used when object can't be created in single
step like in the de-serialization of a complex object.
JavaQuestions.java
import java.util.ArrayList;
import java.util.List;
public JavaQuestions()
{
questions.add("What is class? ");
questions.add("What is interface? ");
questions.add("What is abstraction? ");
questions.add("How multiple polymorphism is
achieved in java? ");
questions.add("How many types of exception
handling are there in java? ");
questions.add("Define the keyword final for
variable, method, and class in java? ");
questions.add("What is abstract class? ");
questions.add("What is multi-threading? ");
}
QuestionManager.java
public class QuestionManager
{
protected Question q;
public String catalog;
public QuestionManager(String catalog)
{
this.catalog = catalog;
}
QuestionFormat.java
public class QuestionFormat extends QuestionManager
{
public QuestionFormat(String catalog)
{
super(catalog);
}
System.out.println("--------------------------------------------------
---------");
}
}
BridgePatternDemo.java
public class BridgePatternDemo
{
public static void main(String[] args)
{
QuestionFormat questions = new
QuestionFormat("Java Programming Language");
questions.q = new JavaQuestions();
questions.delete("what is class?");
questions.display();
questions.newOne("What is inheritance? ");
BankManager.java
// this is the BankManager class i.e. Composite.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@Override
public void add(Employee employee)
{
employees.add(employee);
}
@Override
public Employee getChild(int i)
{
return employees.get(i);
}
@Override
public void remove(Employee employee)
{
employees.remove(employee);
}
@Override
public int getId()
{
return id;
}
@Override
public String getName()
{
return name;
}
@Override
public double getSalary()
{
return salary;
}
@Override
public void print()
{
System.out.println("=====================
=====");
System.out.println("Id =" + getId());
System.out.println("Name =" + getName());
System.out.println("Salary =" + getSalary());
System.out.println("=====================
=====");
Iterator<Employee> it = employees.iterator();
while (it.hasNext())
{
Employee employee = it.next();
employee.print();
}
}
}
Cashier.java
public class Cashier implements Employee
{
/*
* In this class,there are many methods which are
not applicable to cashier
* because it is a leaf node.
*/
private int id;
private String name;
private double salary;
@Override
public void add(Employee employee)
{
// this is leaf node so this method is not
applicable to this class.
}
@Override
public Employee getChild(int i)
{
// this is leaf node so this method is not
applicable to this class.
return null;
}
@Override
public int getId()
{
// TODO Auto-generated method stub
return id;
}
@Override
public String getName()
{
return name;
}
@Override
public double getSalary()
{
return salary;
}
@Override
public void print()
{
System.out.println("=====================
=====");
System.out.println("Id =" + getId());
System.out.println("Name =" + getName());
System.out.println("Salary =" + getSalary());
System.out.println("=====================
=====");
}
@Override
public void remove(Employee employee)
{
// this is leaf node so this method is not
applicable to this class.
}
}
Accountant.java
public class Accountant implements Employee
{
/*
* In this class,there are many methods which are
not applicable to cashier
* because it is a leaf node.
*/
private int id;
private String name;
private double salary;
@Override
public void add(Employee employee)
{
// this is leaf node so this method is not
applicable to this class.
}
@Override
public Employee getChild(int i)
{
// this is leaf node so this method is not
applicable to this class.
return null;
}
@Override
public int getId()
{
// TODO Auto-generated method stub
return id;
}
@Override
public String getName()
{
return name;
}
@Override
public double getSalary()
{
return salary;
}
@Override
public void print()
{
System.out.println("=====================
====");
System.out.println("Id =" + getId());
System.out.println("Name =" + getName());
System.out.println("Salary =" + getSalary());
System.out.println("=====================
====");
}
@Override
public void remove(Employee employee)
{
// this is leaf node so this method is not
applicable to this class.
}
}
CompositePatternDemo.java
public class CompositePatternDemo
{
public static void main(String args[])
{
Employee emp1 = new Cashier(101, "Sohan
Kumar", 20000.0);
Employee emp2 = new Cashier(102, "Mohan
Kumar", 25000.0);
Employee emp3 = new Accountant(103,
"Seema Mahiwal", 30000.0);
Employee manager1 = new
BankManager(100, "Ashwani Rajput", 100000.0);
manager1.add(emp1);
manager1.add(emp2);
manager1.add(emp3);
manager1.print();
}
}
Decorator Pattern
A Decorator Pattern says that just "attach a flexible
additional responsibilities to an object dynamically".
In other words, The Decorator Pattern uses composition
instead of inheritance to extend the functionality of an
object at runtime.
The Decorator Pattern is also known as Wrapper.
VegFood.java
public class VegFood implements Food
{
public String prepareFood()
{
return "Veg Food";
}
FoodDecorator.java
public abstract class FoodDecorator implements Food
{
private Food newFood;
public FoodDecorator(Food newFood)
{
this.newFood=newFood;
}
@Override
public String prepareFood()
{
return newFood.prepareFood();
}
public double foodPrice()
{
return newFood.foodPrice();
}
}
NonVegFood.java
public class NonVegFood extends FoodDecorator
{
public NonVegFood(Food newFood)
{
super(newFood);
}
ChineeseFood.java
public class ChineeseFood extends FoodDecorator
{
public ChineeseFood(Food newFood)
{
super(newFood);
}
DecoratorPatternCustomer.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
choice = Integer.parseInt(br.readLine());
switch (choice)
{
case 1:
{
VegFood vf = new VegFood();
System.out.println(vf.prepareFood());
System.out.println(vf.foodPrice());
}
break;
case 2:
{
Food f1 = new
NonVegFood((Food) new VegFood());
System.out.println(f1.prepareFood());
System.out.println(f1.foodPrice());
}
break;
case 3:
{
Food f2 = new
ChineeseFood((Food) new VegFood());
System.out.println(f2.prepareFood());
System.out.println(f2.foodPrice());
}
break;
default:
{
System.out.println("Other than
these no food available");
}
return;
}
Iphone.java
public class Iphone implements MobileShop
{
@Override
public void modelNo()
{
System.out.println(" Iphone 6 ");
}
@Override
public void price()
{
System.out.println(" Rs 65000.00 ");
}
}
Samsung.java
public class Samsung implements MobileShop
{
@Override
public void modelNo()
{
System.out.println(" Samsung galaxy tab 3 ");
}
@Override
public void price()
{
System.out.println(" Rs 45000.00 ");
}
}
Blackberry.java
public class Blackberry implements MobileShop
{
@Override
public void modelNo()
{
System.out.println(" Blackberry Z10 ");
}
@Override
public void price()
{
System.out.println(" Rs 55000.00 ");
}
}
ShopKeeper.java
public class ShopKeeper
{
private MobileShop iphone;
private MobileShop samsung;
private MobileShop blackberry;
public ShopKeeper()
{
iphone = new Iphone();
samsung = new Samsung();
blackberry = new Blackberry();
}
FacadePatternClient.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
choice = Integer.parseInt(br.readLine());
ShopKeeper sk = new ShopKeeper();
switch (choice)
{
case 1:
{
sk.iphoneSale();
}
break;
case 2:
{
sk.samsungSale();
}
break;
case 3:
{
sk.blackberrySale();
}
break;
default:
{
System.out.println("Nothing You
purchased");
}
return;
}
RealInternetAccess.java
public class RealInternetAccess implements
OfficeInternetAccess
{
private String employeeName;
@Override
public void grantInternetAccess()
{
System.out.println("Internet Access granted
for employee: " + employeeName);
}
}
ProxyInternetAccess.java
public class ProxyInternetAccess implements
OfficeInternetAccess
{
private String employeeName;
private RealInternetAccess realaccess;
@Override
public void grantInternetAccess()
{
if (getRole(employeeName) > 4)
{
realaccess = new
RealInternetAccess(employeeName);
realaccess.grantInternetAccess();
}
else
{
System.out.println("No Internet access
granted. Your job level is below 5");
}
}
ProxyPatternClient.java
public class ProxyPatternClient
{
public static void main(String[] args)
{
OfficeInternetAccess access = new
ProxyInternetAccess("Ashwani Rajput");
access.grantInternetAccess();
}
}
Behavioral Design Patterns
Behavioral design patterns are concerned with the
interaction and responsibility of objects.
In these design patterns, the interaction between the
objects should be in such a way that they can easily
talk to each other and still should be loosely coupled.
That means the implementation and the client should
be loosely coupled in order to avoid hard coding and
dependencies.
There are 12 types of behavioral design patterns:
Chain of Responsibility Pattern
Command Pattern
Interpreter Pattern
Iterator Pattern
Mediator Pattern
Memento Pattern
Observer Pattern
State Pattern
Strategy Pattern
Template Pattern
Visitor Pattern
Null Object
Chain Of Responsibility Pattern
In chain of responsibility, sender sends a request to a
chain of objects. The request can be handled by any
object in the chain.
A Chain of Responsibility Pattern says that just "avoid
coupling the sender of a request to its receiver by
giving multiple objects a chance to handle the request".
For example, an ATM uses the Chain of Responsibility
design pattern in money giving process.
In other words, we can say that normally each receiver
contains reference of another receiver. If one object
cannot handle the request then it passes the same to
the next receiver and so on.
ConsoleBasedLogger.java
public class ConsoleBasedLogger extends Logger
{
public ConsoleBasedLogger(int levels)
{
this.levels = levels;
}
@Override
protected void displayLogInfo(String msg)
{
System.out.println("CONSOLE LOGGER INFO: "
+ msg);
}
}
DebugBasedLogger.java
public class DebugBasedLogger extends Logger
{
public DebugBasedLogger(int levels)
{
this.levels = levels;
}
@Override
protected void displayLogInfo(String msg)
{
System.out.println("DEBUG LOGGER INFO: " +
msg);
}
}
ErrorBasedLogger.java
public class ErrorBasedLogger extends Logger
{
public ErrorBasedLogger(int levels)
{
this.levels = levels;
}
@Override
protected void displayLogInfo(String msg)
{
System.out.println("ERROR LOGGER INFO: " +
msg);
}
}
ChainofResponsibilityClient.java
public class ChainofResponsibilityClient
{
private static Logger doChaining()
{
Logger consoleLogger = new
ConsoleBasedLogger(Logger.OUTPUTINFO);
consoleLogger.setNextLevelLogger(errorLogger);
errorLogger.setNextLevelLogger(debugLogger);
return consoleLogger;
}
chainLogger.logMessage(Logger.OUTPUTINFO,
"Enter the sequence of values ");
chainLogger.logMessage(Logger.ERRORINFO,
"An error is occured now");
chainLogger.logMessage(Logger.DEBUGINFO,
"This was the error now debugging is compeled");
}
}