Factory


here is the 'application class' that uses a factory to create 
instances of some interface.

----------------------------------------------------------------------
public final class Application{

    public static void main(String[] args){
        System.out.println("class: Application, method: main");

        /*
          The CreatureFactory is often not "newed" as it is here.
          It is provided by a call to another part of the system
          statically or at runtime.
        */
        ICreatureFactory icf = new CreatureFactory();
        ICreature ic;
        try{
        ic = icf.newCreatureInstance();
        }catch(Throwable t){
            System.out.println("error error error");
            return;
        }
        System.out.println("This creatures name is: " + ic.getName());
    }
}             
------------------------------------------------------------------------

here is the factory class.
-----------------------------
public final class CreatureFactory implements ICreatureFactory {

    public CreatureFactory(){}

    public ICreature newCreatureInstance() {
        
        /* you can return different objects (that implement ICreature)
           based on args that could be passed in to this call or the 
           state of the system.
           This simply returns a concrete class that implemnts ICreature
        */
        return new Hobbit();
    }

}               
--------------------------------------------------------------------------

the 'concrete' class.
---------------------
public final class Hobbit implements ICreature {
    public String getName(){return "frodo";}
}               
---------------------------------------------------------------------------

A couple of needed interfaces
----------------------------------

public interface ICreatureFactory{
    public ICreature newCreatureInstance()
        throws InstantiationException;
}


public interface ICreature{
    public String getName();
}
----------------------------------------------------------------------------

here is a tar with all the above java classes in it. 
factory