Search This Blog

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

Friday 17 February 2017

Abstract Factory Design Pattern in Java

Intent
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

Motivation
Abstract Factory patterns work around a super-factory which creates other factories.  This factory is also called as factory of factories and comes under Creational pattern. The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes.
In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interface of the factory to create the concrete objects that are part of the theme. The client doesn't know which concrete objects it gets from each of these internal factories, since it uses only the generic interfaces of their products.
This pattern separates the details of implementation of a set of objects from their general usage and relies on object composition, as object creation is implemented in methods exposed in the factory interface.


Applicability
Use the Abstract Factory pattern when
Ø  A system should be independent of how its products are created, composed, and represented.
Ø  A system should be configured with one of multiple families of products.
Ø  A family of related product objects is designed to be used together, and you need to enforce this constraint.
Ø  You want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.

Consequences
The Abstract Factory pattern has the following benefits and liabilities:
Ø  It isolates concrete classes. The Abstract Factory pattern helps you control the classes of objects that an application creates.
Ø  It makes exchanging product families easy. The class of a concrete factory appears only once in an application—that is, where it's instantiated.
Ø  It promotes consistency among products. When product objects in a family are designed to work together, it's important that an application use objects from only one family at a time.
Ø  Supporting new kinds of products is difficult. Extending abstract factories to produce new kinds of Products isn't easy.



Implementation
1.      Create a class Car

public abstract class Car {

   public abstract String getHorsePower();
   public abstract String getSeatingCapacity();
   public abstract String getMileage();
  
   @Override
   public String toString() {
   return "Horse Power : " + this.getHorsePower() +
   ", Seating Capacity : "+this.getSeatingCapacity() +  
         ", Mileage : "+this.getMileage();
   }
}

2.      Create sub class Sedan of class Car
public class Sedan extends Car{

   private String horsePower;
   private String seatingCapacity;
   private String mileage;
  
public Sedan(String horsePower, String seatingCapacity, String mileage) {
         this.horsePower = horsePower;
         this.seatingCapacity = seatingCapacity;
         this.mileage = mileage;
   }

   @Override
   public String getHorsePower() {
         return this.horsePower;
   }

   @Override
   public String getSeatingCapacity() {
         return this.seatingCapacity;
   }

   @Override
   public String getMileage() {
         return this.mileage;
   }

}




3.      Create another sub class SUV of class Car
public class SUV extends Car{
   private String horsePower;
   private String seatingCapacity;
   private String mileage;
  
public SUV(String horsePower, String seatingCapacity, String mileage) {
         super();
         this.horsePower = horsePower;
         this.seatingCapacity = seatingCapacity;
         this.mileage = mileage;
   }

   @Override
   public String getHorsePower() {
         return this.horsePower;
   }

   @Override
   public String getSeatingCapacity() {
         return this.seatingCapacity;
   }

   @Override
   public String getMileage() {
         return this.mileage;
   }
}

4.      Create Abstract factory interface  (Notice that the createCar() method returns an instance of super class Car)
public interface CarAbstractFactory {
   public Car createCar();
}

5.      Now we will create Factory class for Each sub class i.e SedanFactory and SUVFactory class
public class SedanFactory implements CarAbstractFactory{

   private String horsePower;
   private String seatingCapacity;
   private String mileage;

   public SedanFactory(String horsePower, String seatingCapacity, String mileage) {
         this.horsePower = horsePower;
         this.seatingCapacity = seatingCapacity;
         this.mileage = mileage;
   }
         @Override
   public Car createCar() {
         return new Sedan(horsePower,seatingCapacity,mileage);
   }
}

public class SUVFactory implements CarAbstractFactory{

      private String horsePower;
      private String seatingCapacity;
      private String mileage;

      public SUVFactory(String horsePower, String seatingCapacity, String mileage) {
            this.horsePower = horsePower;
            this.seatingCapacity = seatingCapacity;
            this.mileage = mileage;
      }
     
      @Override
      public Car createCar() {
            return new SUV(horsePower,seatingCapacity,mileage);
      }
}

6.      Create a class that will provide the entry point for the client classes to create sub-classes.
public class CarFactory {
public static Car getCar(CarAbstractFactory factory){
   return factory.createCar();
}
}

7.      Write a class with the main() to test your code.
public class Main {
public static void main(String[] args) {
Car sedan=CarFactory.getCar(new SedanFactory("2.2", "5", "15 KMPL"));
   System.out.println("Details of Sedan : "+sedan);
  
   Car suv=CarFactory.getCar(new SUVFactory("3.5", "07", "12 KMPL"));
   System.out.println("Details of SUV : "+suv);
}
}


We will get the following output.

Abstract Factory Design Pattern
Abstract Factory Design Pattern 

Wednesday 25 January 2017

Factory Design Pattern in Java

Factory Design Pattern in Java
Intent
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Motivation
Factory Design pattern is also known as Virtual Constructor, the Factory Method is related to the idea on which libraries work: a library uses abstract classes for defining and maintaining relations between objects. One type of responsibility is creating such objects.
The library knows when an object needs to be created, but not what kind of object it should create, this being specific to the application using the library.

The Factory method works just the same way: it defines an interface for creating an object, but leaves the choice of its type to the subclasses, creation being deferred at run-time.

 A simple real life example of the Factory Method is the Bank Account.
A user wants to open an Account in a bank.  A user can open either a Saving Account, Current Account, Salary Account,  Demat Account based on their requirement.
Depending on the requirement the subclass object for any of the account type can be created can be created.

Applicability
Use the Factory Method pattern when
  •          A class can't anticipate the class of objects it must create.
  •          A class wants its subclasses to specify the objects it creates.
  •          Classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.


Consequences
  •          Factory methods eliminate the need to bind application-specific classes into your code.
  •           Provides hooks for subclasses. Creating objects inside a class with a factory method is always more flexible than creating an object directly. Factory Method gives subclasses a hook for providing an extended version of an object.
  •          Connects parallel class hierarchies. Parallel class hierarchies result when a class delegates some of its responsibilities to a separate class.

 Implementation
We're going to create an Account interface and concrete classes implementing the Account interface.
A factory class AccountFactory would be responsible for returning object.
FactoryPatternDemo  class will use AccountFactory to get an Account object.
It will pass information (Saving / Current / Salary / Demat) to AccountFactory to get the type of object it needs.
Create an Interface Account
public interface Account {
      public void openAccount();
}

Create Classes SavingAccount, SalaryAccount, CurrentAccount, DematAccount which implements the Account interface.
public class SavingAccount implements Account{

      @Override
      public void openAccount() {
            System.out.println("Opening Savings Account");
      }
}

public class CurrentAccount implements Account{

      @Override
      public void openAccount() {
            System.out.println("Opening Current Account"); 
      }
}

public class SalaryAccount implements Account{

      @Override
      public void openAccount() {
            System.out.println("Opening Salary Account");
      }
}

public class DematAccount implements Account{

      @Override
      public void openAccount() {
            System.out.println("Opening Demat Account");   
      }
}

Create the AccountFactory Class which returns Objects of the Subclasses.
public class AccountFactory {
public Account getAccountType(String accountType){
      if(accountType==null){
            return null;
      }
            if(accountType.equalsIgnoreCase("saving")){
                  return new SavingAccount();
            }
            else if(accountType.equalsIgnoreCase("current")){
                  return new CurrentAccount();
            }
            else if(accountType.equalsIgnoreCase("salary")){
                  return new SalaryAccount();
            }
            else if(accountType.equalsIgnoreCase("demat")){
                  return new DematAccount();
            }
      return null;     
}
}

Create the FactoryPatternDemo with the main method
public class FactoryPatternDemo {
public static void main(String[] args) {
      AccountFactory accountFactory=new AccountFactory();
     
      Account saving=accountFactory.getAccountType("saving");
      saving.openAccount();
     
      Account current=accountFactory.getAccountType("current");
      current.openAccount();
     
      Account salary=accountFactory.getAccountType("salary");
      salary.openAccount();
     
      Account demat=accountFactory.getAccountType("demat");
      demat.openAccount();
}
}

Execute the above class , we get the following output.


Factory Design Pattern in Java
Factory Design Pattern in Java