JaiswalTraining

Get the online training



Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com




Corejava
Servlet
Jsp
Php
Hibernate
Ajax
Web Service
Ejb2.1
Ejb3.0
Struts  
Struts2
JPA
Spring
Ibatis
JSF
JSF2.0
CoreJavaDesignPattern
Jquery
Flex
J2EE-Design-Patterns
Jboss7
Maven







Factory Method Pattern
  • The essence of the Factory Pattern is to "Define an interface for creating an object,
    but let the subclasses decide which class to instantiate.
  •  The Factory method lets a class defer instantiation to subclasses.“
  • It creates the object for the client and returns ,but implementation details
    will be hidden to the user.
  • The way to do that is to define your factory as an abstract class or
    interface that has to be implemented by the subclasses that actually do
    the work by creating objects.
Purpose
  • Define an interface for creating an object, but let subclasses decide which class to instantiate.
  • Factory Method lets a class defer instantiation to subclasses.

Applications
  • 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.

Examples of Factory Method Pattern

The Factory Method defines an interface for creating objects, but lets
subclasses decide which classes to instantiate.

Example:-1

Button.java
package tips.pattern.factory;

public abstract class Button {

    public abstract void draw();

}

ButtonFactory.java
package tips.pattern.factory;

public class ButtonFactory {

    public static Button createButton(String os){
        if (os.equals("Windows")){
            return new WindowsButton();
        }else if (os.equals("Linux")){
            return new LinuxButton();
        }
        return null;
    }
}

LinuxButton.java
package tips.pattern.factory;

public class LinuxButton extends Button{

    @Override
    public void draw() {
        System.out.println("Drawing Linux Button");
    }

}

 WindowsButton.java
package tips.pattern.factory;

public class WindowsButton extends Button{

    @Override
    public void draw() {
        System.out.println("Drawing Windows Button");
    }

}

FactoryClient.java
package tips.pattern.factory;

public class FactoryClient {

    public static void main(String[] args) {
        Button windowsButton = 
            ButtonFactory.createButton("Windows");
        windowsButton.draw();

        Button linuxButton = 
            ButtonFactory.createButton("Linux");
        linuxButton.draw();
    }
}

Output:-

Download Zip code

Example:-2

BankABC_AccountConcreteCreator.java
package abc;

import product.BankAccountProduct;
import creator.BankAccountCreator;

public class BankABC_AccountConcreteCreator
 
extends BankAccountCreator {

  public BankAccountProduct createBankAccount
(
String accountType) {
    if ("CHEQUE".equals(accountType)) {
      return new BankABC_ChequeAccountProduct();

    else if ("SAVINGS".equals(accountType)) {
      return new BankABC_SavingsAccountProduct();

    else {
      return null;
    }
  }

}

BankABC_ChequeAccountProduct.java
package abc;

import product.BankAccountProduct;

public class BankABC_ChequeAccountProduct
 
extends BankAccountProduct {

  private double accountBalance = 0.00;

  public BankABC_ChequeAccountProduct() {
    System.out.println("Bank ABC - Cheque
Account : Creating account."
);
  }

  public void depositMoney(double depositAmount) {
    accountBalance += depositAmount;
    System.out.println("Bank ABC - Cheque
Account : Deposit money "

        + depositAmount);
  }

  public void displayBalance() {
    System.out.println("Bank ABC - Cheque Account
: Acount Balance "

        + accountBalance);
  }

  public void withdrawMoney(double withdrawAmount) {
    accountBalance -= withdrawAmount;
    System.out.println("Bank ABC - Cheque Account
 : Withdraw money "

        + withdrawAmount);
  }

}

BankABC_SavingsAccountProduct.java
package abc;

import product.BankAccountProduct;

public class BankABC_SavingsAccountProduct
 
extends BankAccountProduct {

  private double accountBalance = 0.00;

  public BankABC_SavingsAccountProduct() {
    System.out.println("Bank ABC - Savings Account
 : Creating account."
);
  }

  public void depositMoney(double depositAmount) {
    accountBalance += depositAmount;
    System.out.println("Bank ABC - Savings Account
: Deposit money "

        + depositAmount);
  }

  public void displayBalance() {
    System.out.println("Bank ABC - Savings Account
: Acount Balance "

        + accountBalance);
  }

  public void withdrawMoney(double withdrawAmount) {
    accountBalance -= withdrawAmount;
    System.out.println("Bank ABC - Savings Account
: Withdraw money "

        + withdrawAmount);
  }

}

BankAccountCreator.java
package creator;

import product.BankAccountProduct;

public abstract class BankAccountCreator {

  public abstract BankAccountProduct
createBankAccount
(String accountType);

}

BankAccountProduct.java
package product;

public abstract class BankAccountProduct {

  public abstract void depositMoney(double depositAmount);

  public abstract void displayBalance();

  public abstract void withdrawMoney(double withdrawAmount);


BankXYZ_AccountConcreteCreator.java
package xyz;

import product.BankAccountProduct;
import creator.BankAccountCreator;

public class BankXYZ_AccountConcreteCreator
 
extends BankAccountCreator {

  public BankAccountProduct createBankAccount
(
String accountType) {
    if ("CHEQUE".equals(accountType)) {
      return new BankXYZ_ChequeAccountProduct();

    else if ("SAVINGS".equals(accountType)) {
      return new BankXYZ_SavingsAccountProduct();

    else {
      return null;
    }
  // method createBankAccount

// class BankXYZ_AccountConcreteCreator

BankXYZ_ChequeAccountProduct.java
package xyz;

import product.BankAccountProduct;

public class BankXYZ_ChequeAccountProduct
extends 
BankAccountProduct {

  private double accountBalance = 0.00;

  public BankXYZ_ChequeAccountProduct() {
    System.out.println("Bank XYZ - Cheque
Account : Creating account."
);
  // no-arg constructor

  public void depositMoney(double depositAmount) {
    accountBalance += depositAmount;
    System.out.println("Bank XYZ - Cheque Account
 : Deposit money "

        + depositAmount);
  // method depositMoney

  public void displayBalance() {
    System.out.println("Bank XYZ - Cheque Account
: Acount Balance "

        + accountBalance);
  // method displayBalance

  public void withdrawMoney(double withdrawAmount) {
    accountBalance -= withdrawAmount;
    System.out.println("Bank XYZ - Cheque Account
: Withdraw money "

        + withdrawAmount);
  // method withdrawMoney

// class BankXYZ_ChequeAccountProduct

BankXYZ_SavingsAccountProduct.java
package xyz;

import product.BankAccountProduct;

public class BankXYZ_SavingsAccountProduct
extends 
BankAccountProduct {

  private double accountBalance = 0.00;

  public BankXYZ_SavingsAccountProduct() {
    System.out.println("Bank XYZ - Savings Account
: Creating account."
);
  // no-arg constructor

  public void depositMoney(double depositAmount) {
    accountBalance += depositAmount;
    System.out.println("Bank XYZ - Savings Account
: Deposit money "

        + depositAmount);
  // method depositMoney

  public void displayBalance() {
    System.out.println("Bank XYZ - Savings Account
 : Acount Balance "

        + accountBalance);
  // method displayBalance

  public void withdrawMoney(double withdrawAmount) {
    accountBalance -= withdrawAmount;
    System.out.println("Bank XYZ - Savings Account
 : Withdraw money "

        + withdrawAmount);
  // method withdrawMoney

// class BankXYZ_SavingsAccountProduct

BankSystemClient.java
package client;

import product.*;
import creator.*;
import xyz.*;



public class BankSystemClient {

  public static void main(String[] args) {
    BankAccountCreator bankSystemCreator =
new BankXYZ_AccountConcreteCreator();
    BankAccountProduct account = bankSystemCreator
        .createBankAccount("CHEQUE");

    account.depositMoney(10.00);
    account.displayBalance();
    account.withdrawMoney(5.00);
    account.displayBalance();
  }

}

Output:

Download Zip code

Example:-3

Pizza.java

package factory.pizzas;

import java.util.ArrayList;

abstract public class Pizza {
  String name;
  String dough;
  String sauce;
  ArrayList toppings = new ArrayList();

  public String getName() {
    return name;
  }

  public void prepare() {
    System.out.println("Preparing " + name);
  }

  public void bake() {
    System.out.println("Baking " + name);
  }

  public void cut() {
    System.out.println("Cutting " + name);
  }

  public void box() {
    System.out.println("Boxing " + name);
  }

  public String toString() {
    // code to display pizza name and ingredients
    StringBuffer display = new StringBuffer();
    display.append("---- " + name + " ----\n");
    display.append(dough + "\n");
    display.append(sauce + "\n");
    for (int i = 0; i < toppings.size(); i++) {
      display.append((Stringtoppings.get(i"\n");
    }
    return display.toString();
  }
}

package factory.pizzas;

public class CheesePizza extends Pizza {
  public CheesePizza() {
    name = "Cheese Pizza";
    dough = "Regular Crust";
    sauce = "Marinara Pizza Sauce";
    toppings.add("Fresh Mozzarella");
    toppings.add("Parmesan");
  }
}

ClamPizza.java
package factory.pizzas;

public class ClamPizza extends Pizza {
  public ClamPizza() {
    name = "Clam Pizza";
    dough = "Thin crust";
    sauce = "White garlic sauce";
    toppings.add("Clams");
    toppings.add("Grated parmesan cheese");
  }
}

PepperoniPizza.java
package factory.pizzas;

public class PepperoniPizza extends Pizza {
  public PepperoniPizza() {
    name = "Pepperoni Pizza";
    dough = "Crust";
    sauce = "Marinara sauce";
    toppings.add("Sliced Pepperoni");
    toppings.add("Sliced Onion");
    toppings.add("Grated parmesan cheese");
  }
}

PizzaStore.java
package factory.pizzas;

public class PizzaStore {
  SimplePizzaFactory factory;
 
  public PizzaStore(SimplePizzaFactory factory) { 
    this.factory = factory;
  }
 
  public Pizza orderPizza(String type) {
    Pizza pizza;
 
    pizza = factory.createPizza(type);
 
    pizza.prepare();
    pizza.bake();
    pizza.cut();
    pizza.box();

    return pizza;
  }

}


SimplePizzaFactory.java
package factory.pizzas;

public class SimplePizzaFactory {

  public Pizza createPizza(String type) {
    Pizza pizza = null;

    if (type.equals("cheese")) {
      pizza = new CheesePizza();
    else if (type.equals("pepperoni")) {
      pizza = new PepperoniPizza();
    else if (type.equals("clam")) {
      pizza = new ClamPizza();
    else if (type.equals("veggie")) {
      pizza = new VeggiePizza();
    }
    return pizza;
  }
}

VeggiePizza.java
package factory.pizzas;

public class VeggiePizza extends Pizza {
  public VeggiePizza() {
    name = "Veggie Pizza";
    dough = "Crust";
    sauce = "Marinara sauce";
    toppings.add("Shredded mozzarella");
    toppings.add("Grated parmesan");
    toppings.add("Diced onion");
    toppings.add("Sliced mushrooms");
    toppings.add("Sliced red pepper");
    toppings.add("Sliced black olives");
  }
}

PizzaTestDrive.java
package factory.pizzas;

public class PizzaTestDrive {
 
  public static void main(String[] args) {
    SimplePizzaFactory factory = new SimplePizzaFactory();
    PizzaStore store = new PizzaStore(factory);

    Pizza pizza = store.orderPizza("cheese");
    System.out.println("We ordered a " + pizza.getName() "\n");
 
    pizza = store.orderPizza("veggie");
    System.out.println("We ordered a " + pizza.getName() "\n");
  }
}

Output:-


Download Zip code

Example:-4

InterestFactory.java
package com.factory;

import com.model.FDAccountCalculator;
import com.model.InterestCalculator;
import com.model.SavingAccountInterestCalculator;
 
public class InterestFactory {
  public static InterestCalculator create(char type){
    
    switch(type){
    case 's'return new SavingAccountInterestCalculator();
    case 'f'return new FDAccountCalculator();
    }
    return null;
  }
}


FDAccountCalculator.java
package com.model;

public class FDAccountCalculator implements InterestCalculator {
  private double roi=8.0;
  private int duration=3;
  @Override
  public double calculate(double amt) {
    return roi/100.0*amt*duration;
  }

}


InterestCalculator.java
package com.model;

public interface InterestCalculator {
  public double calculate(double amt);
}

SavingAccountInterestCalculator.java
package com.model;

public class SavingAccountInterestCalculator
 
implements InterestCalculator {

  private double roi=3.5;
  @Override
  public double calculate(double amt) {
    return (roi/100.0)*amt/12.0;
  }

}

Test.java
package com.test;

import com.factory.InterestFactory;
import com.model.FDAccountCalculator;
import com.model.SavingAccountInterestCalculator;
import com.service.CalculatorService;

public class Test {
  public static void main(String arg[]){
  
    CalculatorService servicer=new
CalculatorService(InterestFactory.create('s'));
    System.out.println("Interest for Savings
Account for the amount 10000 [Current Month]:
"
+servicer.service(10000));
    servicer=new CalculatorService(InterestFactory
.create
('f'));
    System.out.println("Interest for FD Account for
 the amount 10000 for 3 years: "
+servicer.service(10000));
    
  }
}

Output:-

Downlaod Zip code