Wednesday 3 September 2014

Facade Design Pattern Implementation

Facade Design Pattern

This design pattern falls under structural pattern. As we know the meaning of Facade is the face or front of a building. This pattern helps to hide the complexities of the system and provides an interface to the client. It helps to design a wrapper class or a higher level interface and making subsystems easier to use because it is exposing a simplified interface for the client. It also helps for achieving abstraction and for encouraging loose coupling. For more description refer the below link:

http://www.javatechtipssharedbygaurav.com/2014/03/java-design-patterns-part-2.html

Example :- In any eCommerce website, we can see that order processing screen is working as a facade between Stock and Payment. Now we will implement the same concept in programming. 

User is placing the order without knowing of how internally it is processing. Once the order is being placed, then the façade layer calls the methods of the subsystems like Stock for item availablity check and Payment for processing of the payment. After processing, it returns the control to the user with a confirmation about the order being processed.

1. Stock.java

package com.gaurav.designpattern.facade;

/**
 * @author Gaurav
 * 
 */
public class Stock {
public boolean itemsAvailability(String productId) {
boolean availableFlag = false;
if ("U132897".equalsIgnoreCase(productId)) {
availableFlag = true;
} else if ("U987011".equalsIgnoreCase(productId)) {
availableFlag = true;
}
return availableFlag;
}
}

2. Payment.java

package com.gaurav.designpattern.facade;

/**
 * @author Gaurav
 * 
 */
import java.util.HashMap;

public class Payment {
public String getPayment(HashMap<String, String> cardDetailsMap) {
 boolean authFlag = true;
 String status = "Failed";
 if(authFlag){
  System.out.println("Payment is approved successfully - by Bank");
  status = "Success";
 }
 return status;
}
}

3. OrderFacadeInterface.java

package com.gaurav.designpattern.facade;

/**
 * @author Gaurav
 * 
 */
import java.util.HashMap;

public class OrderFacadeInterface {
private Stock stock = new Stock();
private Payment payment = new Payment();
public boolean placeOrder(HashMap<String, String> cardDetails, String productId){
boolean placeOrderStatus = false; 
boolean itemAvailability = stock.itemsAvailability(productId);
String paymentStatus = null;
if(itemAvailability){
System.out.println(productId+ " is available in the stock");
paymentStatus = payment.getPayment(cardDetails);
}
if("Success".equalsIgnoreCase(paymentStatus)){
placeOrderStatus = true;
}
return placeOrderStatus;
}
}

4. EcommerceMerchant.java

package com.gaurav.designpattern.facade;

/**
 * @author Gaurav
 * 
 */
import java.util.HashMap;

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

String productId = "U987011";

HashMap<String, String> cardDetails = new HashMap<String, String>();
cardDetails.put("CardNumber", "2134567821345698");
cardDetails.put("CVV", "012");
cardDetails.put("ExpiryDate", "10/15");
OrderFacadeInterface ofi = new OrderFacadeInterface();
boolean orderStatus = ofi.placeOrder(cardDetails, productId);
System.out.println("Order is placed successfully : "+orderStatus);
}
}

Result :- 

U987011 is available in the stock
Payment is approved successfully - by Bank
Order is placed successfully : true

Tuesday 2 September 2014

Decorator Design Pattern Implementation

Decorator Design Pattern

As we know that Decorator design pattern belongs to Structural pattern. This allows to add new functionality to an existing object either statically or dynamically, without affecting the behavior of other objects from the same class.

As per GOF "Allows for the dynamic wrapping of objects in order to modify their existing responsibilities and behaviors."

In other words, decorator design pattern allows us to construct a wrapper around the object by enhancing its functionality. The basic thing is we are wrapping the original object through decorated object. 

The below elements are the participants of the Decorator Design pattern:
  • Component – This defines the interface for objects that can have responsibilties added either statically or dynamically.
  • Concrete Component - This is simply an implementation of this interface.
  • Decorator - This has a reference to a Component, and also implements the  Component interface.
  • Concrete Decorator - This just adds extra responsibilities to the original Component.
Example :- In the below example Car is the Component, HatchbackCar is the Concrete Component, CarDecor is the Decorator and PremiumHatchbackCar & LuxurySportsCar is the Concrete Decorator.

1. Car.java

package com.gaurav.designpattern.decorator;

/**
 * @author gaurav
 *
 */
public interface Car {
public void addedFeatures();
}

2. HatchbackCar.java

package com.gaurav.designpattern.decorator;

/**
 * @author gaurav
 *
 */
public class HatchbackCar implements Car{

@Override
public void addedFeatures() {
System.out.println("This is a Basic HatchBack Car, No Premium facilities added.");
}

}

3. CarDecor.java

package com.gaurav.designpattern.decorator;

/**
 * @author gaurav
 *
 */
public class CarDecor implements Car{
protected Car car;
public CarDecor(Car c){
this.car = c;
}
@Override
public void addedFeatures() {
this.car.addedFeatures();
}
 
}

4. PremiumHatchbackCar.java

package com.gaurav.designpattern.decorator;

/**
 * @author gaurav
 *
 */
public class PremiumHatchbackCar extends CarDecor {

public PremiumHatchbackCar(Car c) {
super(c);
}

@Override
public void addedFeatures() {
car.addedFeatures();
System.out
.println("Few premium facilities are available in Hyundai Elite i20 like Power Windows-Front, Low Fuel Warning Light, Fabric Upholstery e.t.c");
}
}

5. LuxurySportsCar.java

package com.gaurav.designpattern.decorator;

/**
 * @author gaurav
 * 
 */
public class LuxurySportsCar extends CarDecor {

public LuxurySportsCar(Car c) {
super(c);
}

@Override
public void addedFeatures() {
car.addedFeatures();
System.out
.println("Luxury facilities are available in Mercedes-Benz A Class like Multi-function steering wheel, Bluetooth® telephony, Sunroof, Retrofitted anti-glare film e.t.c");
}
}

6. DecoratorDesignPatternDemo.java

package com.gaurav.designpattern.decorator;

/**
 * @author gaurav
 * 
 */
public class DecoratorDesignPatternDemo {
public static void main(String args[]) {
Car premiumHatchbackCar = new PremiumHatchbackCar(new HatchbackCar());
premiumHatchbackCar.addedFeatures();
System.out.println("*************************************************");

Car luxurySportsCar = new PremiumHatchbackCar(new LuxurySportsCar(
new HatchbackCar()));
luxurySportsCar.addedFeatures();
System.out.println("*************************************************");

}
}

Result:-

This is a Basic HatchBack Car, No Premium facilities added.
Few premium facilities are available in Hyundai Elite i20 like Power Windows-Front, Low Fuel Warning Light, Fabric Upholstery e.t.c
*************************************************
This is a Basic HatchBack Car, No Premium facilities added.
Luxury facilities are available in Mercedes-Benz A Class like Multi-function steering wheel, Bluetooth® telephony, Sunroof, Retrofitted anti-glare film e.t.c
Few premium facilities are available in Hyundai Elite i20 like Power Windows-Front, Low Fuel Warning Light, Fabric Upholstery e.t.c
*************************************************





Monday 1 September 2014

Composite Design Pattern Implementation

Composite Design Pattern

A composite object is an object designed as a composition of one-or-more similar type of objects, all showing similar functionality. For more details about Composite design pattern description please refer this link : http://www.javatechtipssharedbygaurav.com/2014/03/java-design-patterns-part-2.html



In a School, there are tree structure for employees. At top, there is a Director. There are two employees, School principal is reporting to director and Head Of admin Department is also reporting to director and further Pricipal has two teachers one is Math Teacher and another one is Physics Teacher. Now our target is to print employees details from top to bottom.

1. SchoolEmployee.java

package com.gaurav.designpattern.composite;

/**
 * @author gaurav
 * 
 */
public interface SchoolEmployee {
public String getEmployeeName();
public Double getEmployeeSalary();
public int getEmployeeId();
public String getEmployeeDesig();
public void getEmployeeDetails();
public int getHolidayLeaves();
public boolean addEmployee(SchoolEmployee schoolEmployee);
}

2. SchoolPricipal.java

package com.gaurav.designpattern.composite;

/**
 * @author gaurav
 * 
 */
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class SchoolPricipal implements SchoolEmployee{
List<SchoolEmployee> schoolEmployeeList = new ArrayList<SchoolEmployee>();
private int employeeId;
private String employeeName;
private Double employeeSalary;
private String employeeDesig;
private int holidayLeaves;
public SchoolPricipal(int empId, String name, Double salary, String desig){
this.employeeId = empId;
this.employeeName = name;
this.employeeSalary = salary;
this.employeeDesig = desig;
}
@Override
public void getEmployeeDetails() {
System.out.println("-----------------------------------");
System.out.println("Employee name is : " + getEmployeeName()
+ "\nSalary : " + getEmployeeSalary() + "\nID : "
+ getEmployeeId() + "\nDesig : " + getEmployeeDesig()
+ "\nHoliday Leaves : " + getHolidayLeaves());
System.out.println("-----------------------------------");
Iterator<SchoolEmployee> employeeIterator = schoolEmployeeList
.iterator();
while (employeeIterator.hasNext()) {
SchoolEmployee schoolEmployee = employeeIterator.next();
schoolEmployee.getEmployeeDetails();
}
}
@Override
public Double getEmployeeSalary() {
return employeeSalary;
}

@Override
public int getHolidayLeaves() {
holidayLeaves = 21;
return holidayLeaves;
}

@Override
public boolean addEmployee(SchoolEmployee schoolEmployee) {
boolean addStatus  = schoolEmployeeList.add(schoolEmployee);
return addStatus;
}

@Override
public String getEmployeeName() {
return employeeName;
}

@Override
public int getEmployeeId() {
return employeeId;
}

@Override
public String getEmployeeDesig() {
return employeeDesig;
}
}

3. SchoolTeacher.java

package com.gaurav.designpattern.composite;

/**
 * @author gaurav
 * 
 */
import java.util.ArrayList;
import java.util.List;

public class SchoolTeacher implements SchoolEmployee{
List<SchoolEmployee> schoolEmployeeList = new ArrayList<SchoolEmployee>();
private int employeeId;
private String employeeName;
private Double employeeSalary;
private String employeeDesig;
private int holidayLeaves;
public SchoolTeacher(int empId, String name, Double salary, String desig){
this.employeeId = empId;
this.employeeName = name;
this.employeeSalary = salary;
this.employeeDesig = desig;
}
@Override
public void getEmployeeDetails() {

System.out.println("-----------------------------------");
System.out.println("Employee name is : " + getEmployeeName()
+ "\nSalary : " + getEmployeeSalary() + "\nID : "
+ getEmployeeId() + "\nDesig : " + getEmployeeDesig()
+ "\nHoliday Leaves : " + getHolidayLeaves());
System.out.println("-----------------------------------");
}
@Override
public Double getEmployeeSalary() {
return employeeSalary;
}

@Override
public int getHolidayLeaves() {
holidayLeaves = 11;
return holidayLeaves;
}
@Override
public boolean addEmployee(SchoolEmployee schoolEmployee) {
boolean addStatus  = schoolEmployeeList.add(schoolEmployee);
return addStatus;
}

@Override
public String getEmployeeName() {
return employeeName;
}

@Override
public int getEmployeeId() {
return employeeId;
}

@Override
public String getEmployeeDesig() {
return employeeDesig;
}
}

4. CompositeDesignPatternDemo.java

package com.gaurav.designpattern.composite;

/**
 * @author gaurav
 * 
 */
public class CompositeDesignPatternDemo {

public static void main(String[] args) {
SchoolEmployee schoolEmployee1 = new SchoolTeacher(1, "Arjun Prasad",
19000.00, "Math Teacher");
SchoolEmployee schoolEmployee2 = new SchoolTeacher(7, "Deepti Mohanty",
25000.00, "Physics Teacher");
SchoolEmployee pricipal = new SchoolPricipal(1001, "Anurag Kumar", 55000.00,
"Pricipal");

pricipal.addEmployee(schoolEmployee1);
pricipal.addEmployee(schoolEmployee2);

SchoolEmployee schoolEmployee3 = new SchoolTeacher(10, "Kirti Ranjan", 56000.00,
"Head Of admin Department");
SchoolPricipal director = new SchoolPricipal(5001, "Gaurav Kumar", 95000.00,
"Trustee Head");
director.addEmployee(schoolEmployee3);
director.addEmployee(pricipal);
director.getEmployeeDetails();
}
}


Result :-

-----------------------------------
Employee name is : Gaurav Kumar
Salary : 95000.0
ID : 5001
Desig : Trustee Head
Holiday Leaves : 21
-----------------------------------
-----------------------------------
Employee name is : Kirti Ranjan
Salary : 56000.0
ID : 10
Desig : Head Of admin Department
Holiday Leaves : 11
-----------------------------------
-----------------------------------
Employee name is : Anurag Kumar
Salary : 55000.0
ID : 1001
Desig : Pricipal
Holiday Leaves : 21
-----------------------------------
-----------------------------------
Employee name is : Arjun Prasad
Salary : 19000.0
ID : 1
Desig : Math Teacher
Holiday Leaves : 11
-----------------------------------
-----------------------------------
Employee name is : Deepti Mohanty
Salary : 25000.0
ID : 7
Desig : Physics Teacher
Holiday Leaves : 11
-----------------------------------