Ubuntu insights, Programming in groovy, java, et als!

Wednesday, June 20, 2012

Design Patterns: Factory Method Pattern

/**
* A simple implementation of Factory Method Pattern
* using a real time CricketPlayer example
*/


//Base
public interface CricketPlayer{
    public String play();
}


//Subclass
class Bowler implements CricketPlayer{
    public String  play (){
        return "takes a wicket";
    }
}


//Subclass
class Batsman implements CricketPlayer{
    public String  play (){
        return "hits a six";
    }
}


//Factory class - contains the logic of instatiating players
public class CricketPlayerFactory{
    CricketPlayer player;
   
    public CricketPlayer getPlayerWho(String does){
        if(does.equals("bats"))
            player = new Batsman();
        else if(does.equals("bowls"))
            player = new Bowler();
        return player;              
    }
}


//Factory method implementation
public class FactoryImplementation{
    public static void main(String args){
        //create a factory
        CricketPlayerFactory factory = new CricketPlayerFactory();
        //ask factory to instantiate the player
        CricketPlayer player = factory.getPlayerWho("bats");
        //use the player
        System.out.prinln(player. play ());
    }
}

1 comments:

nasir husain said...

thanks for this information .
you can find factory design pattern in simple and easy to understand language in a detail on
http://www.itsoftpoint.com/?page_id=2666

Post a Comment