Friday, August 12, 2011

JAVA SAMPLE CODE OF FACTORY DESIGN PATTERN


/*
 Design pattern : Factory Design Pattern
 we have a super class and sub-classes and we need to return object of any subclass according to the data  
 provided  then we use the Factory Pattern.

 This is a program of Factory Design pattern

 */



/**
 *
 * @author RK
 */

class Department{
    String name;
    String charCode;

    public Department(String name,String charCode) {
        this.name=name;
        this.charCode=charCode;
    }

    public String getName(){
        return name;
    }
    public String getCharCode(){
        return charCode;
    }
}

class Sales extends Department{

    public Sales(String name){
        super(name,"S");
        System.out.println("Your Department in "+name+" department");
    }
}

class Purchase extends Department{
    public Purchase(String name){
        super(name,"p");
        System.out.println("Your Department in "+name+" department");
    }
}

class Account extends Department{
    public Account(String name){
        super(name,"a");
        System.out.println("Your Department in "+name+" department");
    }
}


public class FactoryPattern {

    public static void main(String RK[]){
        FactoryPattern start=new FactoryPattern();
        //Department d=start.getDepartment("Purchase","P");
        Department d=start.getDepartment(RK[0],RK[1]);
        System.out.println("Department name : "+d.name);
        System.out.println("Department code : "+d.charCode);
     
    }
    public Department getDepartment(String name,String charCode){
        if(charCode.equals("P")){
            return new Purchase(name);
        }else if(charCode.equals("S")){
            return new Sales(name);
        }else if(charCode.equals("A")){
            return new Account(name);
        }else{
            return null;
        }
    }
}

No comments:

Post a Comment