Static Factory Methods

can anybody guide me on what static factory methods are, how they are invoked and there advantages over constructors.

Joshua Bloch has a good bit on it in his book Effective Java. If you don't have that then I suggest Google as it's been explained to death before. Static factory methods are for all intents and purposes when you provide a static method that returns an instance of a given object rather than having a public constructor.

Similar Messages

  • Static factory methods, instead of constructor

    Hi All,
    why we use static factory methods, instead of constructor.
    Apart from Singleton class , what is use of static factory methods ?
    Thanks in Advance,
    Rishi

    One reason for using factories is that they simplify creating instances of immutable classes that might otherwise have messy constructors with lots of arguments.

  • Apply static method requirements on class (Static interface methods)?

    I have a set of classes where is class is identified with a unique ID number. So each class has a public static int getId() method. Each class also has either a constructor that takes a byte array or a static factory method that takes a byte array.
    I would like to maintain a hashmap of these classes keyed to the ID's however I am not sure how to have some interface of abstract parent class that requires each of these classes to implement these static methods.
    What I was hoping to do was something like this>>>
         public interface MyClasses{
              static MyClasses createInstance(byte[] data);
         HashMap<Integer, MyClasses> map;
         public void init() {
              map = new HashMap<Integer, MyClasses>();
              map.put(Class1.getId(), Class1.class);
              map.put(Class2.getId(), Class2.class);
         public void createInstance (int id, byte[] data) {
              map.get(id).createInstance(data);
         }Is there some way I could do this?

    What about something like this?
    public interface Initializable
         public void initialize(byte[] data);
    public class Factory
         private final Map<Integer, Initializable> map = new HashMap<Integer, Initializable>();
            public void registerClass(int id, Class klass)
                    if (! Initializable.class.isAssignableFrom(klass))
                             // you may also want to ensure the class declares a parameterless constructor
                             throw new IllegalArgumentException("duff class");
                    if (this.map.keySet().contains(id))
                             throw new IllegalArgumentException("duff id");
              this.map.put(id, klass);
         public Initializable createInstance(int id, byte[] data)
                    // need some exception handling of course
              Initializable i = map.get(id).newInstance();
                    i.initialize(data);
                    return i;
    }

  • Problem in factory method, how to pass arguments ?

    Hello it's me again :)
    here's the code :
    package print;
    import java.util.*;
    import static print.Print.*;
    interface Fact<T> {
    T create(String n);;
    T create ();
    class PetColl {
          public String toString() {
          return getClass().getSimpleName();
          static List<Fact<? extends Pet>> petSpecies=
          new ArrayList<Fact<? extends Pet>>();
          static {
          // Collections.addAll() gives an "unchecked generic
          // array creation ... for varargs parameter" warning.
               petSpecies.add(new Cymric.Factory());
               petSpecies.add(new EgyptianMau.Factory());
               petSpecies.add(new Hamster.Factory());
               petSpecies.add(new Manx.Factory());
               petSpecies.add(new Mouse.Factory());
               petSpecies.add(new Pug.Factory());
               petSpecies.add(new Mutt.Factory());
               petSpecies.add(new Rat.Factory());
          private static Random rand = new Random(47);
          public static Pet createRandom() {
          int n = rand.nextInt(petSpecies.size());
          return petSpecies.get(n).create();
          public Pet[] createArray(int size) {
               Pet[] result = new Pet[size];
               for(int i = 0; i < size; i++)
               result[i] = createRandom();
               return result;
          public ArrayList<Pet> arrayList(int size) {
               ArrayList<Pet> result = new ArrayList<Pet>();
               Collections.addAll(result, createArray(size));
               return result;
    class Individual implements Comparable<Individual> {
         private static long counter = 0;
         private final long id = counter++;
         private String name;
         public Individual(String name) { this.name = name; }
         // ?name? is optional:
         public Individual() {}
         public String toString() {
         return getClass().getSimpleName() +
         (name == null ? "" : " " + name);
         public long id() { return id; }
         public boolean equals(Object o) {
         return o instanceof Individual &&
         id == ((Individual)o).id;
         public int hashCode() {
         int result = 17;
         if(name != null)
         result = 37 * result + name.hashCode();
         result = 37 * result + (int)id;
         return result;
         public int compareTo(Individual arg) {
         // Compare by class name first:
         String first = getClass().getSimpleName();
         String argFirst = arg.getClass().getSimpleName();
         int firstCompare = first.compareTo(argFirst);
         if(firstCompare != 0)
         return firstCompare;
         //second compare by name
         if(name != null && arg.name != null) {
         int secondCompare = name.compareTo(arg.name);
         if(secondCompare != 0)
         return secondCompare;
         }//third compare by id
         return (arg.id < id ? -1 : (arg.id == id ? 0 : 1));
    class Pets {
          public static final PetColl creator =
          //new LiteralPetCreator();
               new PetColl();
          public static Pet randomPet() {
          return creator.createRandom();
          public static Pet[] createArray(int size) {
          return creator.createArray(size);
          public static ArrayList<Pet> arrayList(int size) {
          return creator.arrayList(size);
    class Person extends Individual {
    String name;
    public static class Factory implements Fact<Person>{
    public Person create(String name){
         Person.name=name;
         return new Person(); }
    public Person create(){return new Person();}
    class Pet  extends Individual {
    class Dog extends Pet {
    class Mutt extends Dog {
          public static class Factory implements Fact<Mutt> {
               public  Mutt create(String name){return new Mutt(name);}
               public  Mutt create () {return new Mutt();}
    class Pug extends Dog {
          public static class Factory implements Fact<Pug> {
               public  Pug create(String name){return new Pug(name);}
               public  Pug create () {return new Pug();}
    class Cat extends Pet {
    class EgyptianMau extends Cat {
          public static class Factory implements Fact<EgyptianMau> {
               public  EgyptianMau create(String name){return new EgyptianMau(name);}
               public  EgyptianMau create () {return new EgyptianMau();}
          class Manx extends Cat {
               public static class Factory implements Fact<Manx> {
                    public  Manx create(String name){return new Manx(name);}
                    public  Manx create () {return new Manx();}
         class Cymric extends Manx {
              public static class Factory implements Fact<Cymric> {
                    public  Cymric create(String name){return new Cymric(name);}
                    public  Cymric  create () {return new Cymric();}
    class Rodent extends Pet {
    class Rat extends Rodent {
          public static class Factory implements Fact<Rat> {
               public  Rat create(String name){return new Rat(name);}
               public  Rat create () {return new Rat();}
    class Mouse extends Rodent {
          public static class Factory implements Fact<Mouse> {
               public  Mouse create(String name){return new Mouse(name);}
               public  Mouse create () {return new Mouse();}
    class Hamster extends Rodent {
          public static class Factory implements Fact<Hamster> {
               public  Hamster create(String name){return new Hamster(name);}
               public  Hamster create () {return new Hamster();}
    public class Test {
          public static void main(String[] args) {
              for(Pet p:Pets.creator.arrayList(25)){
          PetCount.petC.count(p.getClass().getSimpleName());
              print(p.getClass().getSimpleName());}
      class PetCount {
          static class PetCounter extends HashMap<String,Integer> {
          public  void count(String type) {
          Integer quantity = get(type);
          if(quantity == null)
          put(type, 1);
          else
          put(type, quantity + 1);
         public static PetCounter petC= new PetCounter();
      }and here's my problem:
    I'm trying to fill up list using factory method but in a fact that I want to have two constructors, I have a problem to set field name of objects of those classes. Is there any possibility to use in that way some factory method to create that list ?
    In Person class I've tried to set it in factory method before creating an object, but as you know that option is only alvailable for static fields which i don't want to be static.

    I for one have no idea what you're asking, and what you seem to be saying doesn't make sense.
    I'm trying to fill up list using factory method but in a fact that I want to have two constructors,Two constructors for what? The factory class? The classes that the factory instantiates?
    I have a problem
    to set field name of objects of those classes. Is there any possibility to use in that way some factory method to
    create that list ?What?
    In Person class I've tried to set it in factory method before creating an object, but as you know that option is only alvailable for static fields which i don't want to be static.That doesn't make any sense. A Factory can easily set fields in the objects it creates on the fly (not static).

  • Meaning of factory method in abap objects

    Hi,
    Can anybody help me in understanding the meaning of factory method in abap object? what is the importance of this?
    Regards
    Sudhansu

    Hi Krish and Sudhansu,
    Design patterns are solutions which are already verified and known by many developers. That is why it is worth to use them. There is no need to reinvent the wheel in many cases.
    I would recommend book which is placed in the ABAP world:
    http://www.sap-press.com/products/Design-Patterns-in-Object%252dOriented-ABAP-(2nd-Edition).html
    Although Java language has intuitive syntax, there are some special things in ABAP development so it is better to check solutions adjusted for ABAP editor.
    The most common usage of factory pattern is to simplify object creation.
    - By one method call you provide required parameters and do all initializations, including dependent objects.
    - Class can have many factory methods, if you want to provide more ways of initialization.
    - Factory method is usually static in the class and they return initialized instance of object for this class.
    - There is naming convention to start factory method name with "create" - easy to recognize pattern.
    - If you set property of class to "private instantiation" then you force to use factory method for object creation. In this way it is really simple to find all places where object are created with given set of input parameters - find references of factory method.
    Factory pattern becomes even more powerful if we add inheritance. Factory method returns basic object (like ZCL_VEHICLE) but its implementation can return different subclass instance, depending on input parameter (ZCL_CAR, ZCL_TRAIN etc). Each instance can implement differently behavior (methods implementation), but these are object oriented techniques.
    Regards,
    Adam

  • Factory method

    Hey all, I am tying to learn factory method and working on an example from the Oreilly AS3 Design patterns book. I am attempting figure out how all the classes work together in this design pattern and I have a question I am hoping someone might be able clearify for me.
    In the document class "Main"  I have the following code in the constructor
    // instantiate concrete shape creators
    var unfilledShapeCreator:ShapeCreator = new UnfilledShapeCreator( );
    // draw unfilled shapes  NOTE: draw() is a method of the ShapeCreator class
    unfilledShapeCreator.draw(UnfilledShapeCreator.CIRCLE, this.stage, 50, 75);
    I get what is going on there, so I open up the 'UnfilledShapeCreator" class and it has the following:
    package shapecreators
         /* Concrete Creator class */
         public class UnfilledShapeCreator extends ShapeCreator
              public static const CIRCLE :uint = 0;
              public static const SQUARE :uint = 1;
              //implement the createShape factory method from the ShapeCreator Class.
              override protected function createShape(cType:uint):ShapeWidget
                   if (cType == CIRCLE)
                        trace("Creating new circle shape");
                        return new CircleWidget( ); //Instantiates circleWidge Product Class
                   } else if (cType == SQUARE) {
                        trace("Creating new square shape");
                        return new SquareWidget( ); //Instantiates square Widge Product Class
                   } else {
                        throw new Error("Invalid kind of shape specified");
                        return null;
    and the ShapeCreator class is as follows
    package shapecreators
         /* Defines the abstract interface for the creator classes */
         import flash.display.DisplayObjectContainer;
         import flash.errors.IllegalOperationError;
         // ABSTRACT Class (should be subclassed and not instantiated)
         public class ShapeCreator
              public function draw(cType:uint, target:DisplayObjectContainer, xLoc:int, yLoc:int):void
                   var shape = this.createShape(cType);
                   shape.drawWidget( );
                   shape.setLoc(xLoc, yLoc); // set the x and y location
                   target.addChild(shape); // add the sprite to the display list
              // ABSTRACT Method (must be overridden in a subclass)
              protected function createShape(cType:uint):ShapeWidget
                   throw new IllegalOperationError("Abstract method: must be overridden in a subclass");
                   return null;
    My question is: how does the cType  parameter get passed into the createShape method?  This method does not seem to get called from anywhere or any other class.   I see how FilledShapeCreator.CIRCLE gets passed to the  draw method in the ShapeCreator class, but the createShape method is never called like the draw method is.
    Is it because createShape is called within the draw function?
    I am quite sure it is a simple answer, but it has me completely lost.
    Thanks,

    Yes, it is called by super class in line:
    var shape = this.createShape(cType);
    By the way, I don't know where you got code but it is a pretty bad practice not type variables. Good compiler should not even allow you to compile. The line above should be:
    var shape:ShapeWidget = this.createShape(cType);

  • Factory method usage, creating the correct Image subclass

    Hi, I created a factory method
      public enum ImgType {
        SINGLE, STRIP, SPRITE_SHEET
    public static Image createImage(ImgType imgType) {
        switch (imgType) {
          case SINGLE:
            return new MyImage1(0, 0);
          case SPRITE_SHEET:
            return new MyImage2("", 0, 0);
          case STRIP:
            return new MyImage3("", 0, 0);
          default:
            throw new IllegalArgumentException("The image type " + imgType + " is not recognized.");
      }that creates different images based on the enum type provided.
    and heres is a usage of that function
      public BufferedImage loadAwtImage(ImageInputStream in, String imgName,  ImageTypeFactory.ImgType imgType) throws IOException {
        BufferedImage img = imgLoader.loadImage(in);
        BufferedImage imgsubType = ImageTypeFactory.createImage(imgType);  // Convert to real Image type
        addAwtImg(imgName, imgsubType);
        return imgsubType;
      }In a test:
    imgLib.loadAwtImage(imageStream, "cursor", ImageTypeFactory.ImgType.SPRITE_SHEET);Is it 'good' that in the test I can say(using the imgType enum) what sort of Image should be returned?
    doesn't this expose the working of the class to the outside, on the other hand I don't know howto create the correct sub image based on an image loaded.
    I use subImages to allow selection within the image, like the 3th 'tile' within an imageStrip returns just that cropped image.
    Before I had List<Image> and List<List<Image>> and now I can just return Images in 1 method instead of 2,3 by using lists.
    Edited by: stef569 on Dec 12, 2008 11:05 AM

    creates specifications... :p
    *  load the BufferedImage from the ImageInputStream
    * add it to the cache keyed by the imgName
    * @return a BufferedImage, or a custom subclass based on the imgType
    * @throws IOException when the img could not be loaded
    public BufferedImage loadAwtImage(ImageInputStream in, String imgName,  ImageTypeFactory.ImgType imgType) throws IOException I can test it, but the ImageTypeFactory.ImgType imgType parameter looks wrong to me.
    if you see this in a class method would you change it/find a better way.

  • Unusual use of interface defining static factory class with getInstance

    This question is prompted by a recent New to Java forum question ask about the differences between Interfaces and Abstract classes. Of course one of the standard things mentioned is that interfaces cannot actually implement a method.
    One of my past clients, one of the 500 group, uses interfaces as class factories. The interface defines a pubic static class with a public static method, getInstance, that is called to generate instances of a class that implements the interface.
    This architecture was very object-oriented, made good use of polymorphism and worked very well. But I haven't seen this architecture used anywhere else and it seemed a little convoluted.
    Here is a 'pseudo' version of the basic interface template and use
    -- interface that defines public static factory class and getInstance method
    public interface abc {
        public static class FactoryClass
            public static abc getInstance ()
                return (abc) FactoryGenerator(new abcImpl(), abc.class);
    -- call of interface factory to create an instance
    abc myABC = abc.Factory.getInstance();1. Each main functional area ('abc' in the above) has its own interface factory
    2. Each main functional area has its own implementation class for that interface
    3. There is one generator (FactoryGenerator) that uses the interface class ('abc.class') to determine which implementation class to instantiate and return. The generator class can be configured at startup to control the actual class to return for any given interface.
    I should mention that the people that designed this entire architecture were not novices. They wrote some very sophisticated multi-threaded code that rarely had problems, was high performance and was easy to extend to add new functionality (interfaces and implementing classes) - pretty much plug-n-play with few, if any, side-effects that affected existing modules.
    Is this a best-practices method of designing factory classes and methods? Please provide any comments about the use of an architecture like this.

    Thanks for the feedback.
    >
    I don't see how 'the generator class can be configured at startup to control the actual class to return for any given interface' can possibly be true given this pseudo-code.
    >
    I can see why that isn't clear just from what is posted.
    The way it was explained to me at the time is that the interface uses standard naming conventions and acts like a template to make it easy to clone for new modules: just change 'abc' to 'def' in three places and write a new 'defImpl' class that extends the interface and the new interface and class can just 'plug in' to the framework.
    The new 'defImpl' class established the baseline functionality that must be supported. This line
    return (abc) FactoryGenerator(new abcImpl(), abc.class);uses the initial version of the new class that was defined, 'abcImpl()', when calling the FactoryGenerator and it acted as a 'minimum version supported'. The generator class could use configuration information, if provided, to provide a newer class version that would extend this default class. Their reasoning was that this allowed the framework to use multiple versions of the class as needed when bugs got fixed or new functionality was introduced.
    So the initial objects would be an interface 'abc' and a class 'abcImpl'. Then the next version (bug fixes or enhancements) would be introduced by creating a new class, perhaps 'abcImpl_version2'. A configuration parameter could be passed giving 'abcImpl' as the base class to expect in the FactoryGenerator call and the generator would actually create an instance of 'abcImpl_version2' or any other class that extended 'abcImpl'.
    It certainly go the job done. You could use multiple versions of the class for different environments as you worked new functionality from DEV, TEST, QA and PRODUCTION environments without changing the basic framework.
    I've never seen any Java 'pattern' that looks like that or any pattern where an interface contained a class. It seemed really convoluted to me and seems like the 'versioning' aspect of it could have been accomplished in a more straightforward manner.
    Thanks for the feedback. If you wouldn't mind expanding a bit on one comment you made then I will mark this ANSWERED and put it to rest.
    >
    I don't mind interfaces containing classes per se when necessary
    >
    I have never seen this except at this one site. Would you relate any info about where you have seen or used this or when it might be necessary?

  • Factory method generateRandomCircle: "cannot resolve symbol"

    I have written 2 classes: Point and Circle, which uses Point objects in order to create a Circle object. I have created a factory method for Point, which creates random Point objects and a for Circle, which does the same. "newRandomInstance" works fine for Point, but "generateRandomCircle" throws a "cannot resolve symbol" error. "main" is inside Point class. What's the problem?
    Thanks
    ================================================
    import java.io.*;
    import java.lang.*;
    import java.util.*;
    public class Circle implements Cloneable
    public static Circle generateRandomCircle()
    int a= (int) (Math.random()* Short.MAX_VALUE);
    int b= (int) (Math.random()* Short.MAX_VALUE);
    Point p=new Point(a,b);
    int r= (int) (Math.random()* Short.MAX_VALUE);
    Circle c= new Circle(p,r);
    return c;
    ===============================================
    import java.io.*;
    import java.lang.*;
    import java.util.*;
    public class Point implements Cloneable, Comparable
    public static Point newRandomInstance()
    int x = (int) (Math.random() * Short.MAX_VALUE);
    int y = (int) (Math.random() * Short.MAX_VALUE);
    return new Point(x,y);
    public static void main (String[] args)
    Circle cRandom= generateRandomCircle(); //doesn't work
    System.out.println(cRandom.getCenter()+" "+ cRandom.getRadius());
    Point randomP= newRandomInstance(); //works OK
    randomP.printPoint();
    }

    I tried "Circle cRandom=
    Circle.generateRandomCircle(); " instead of "Circle
    cRandom= generateRandomCircle();" and it worked. Why
    did this happen?Because generateRandomCircle() exists in class Circle and not in class Point where your are trying to use it.
    >
    Function "newRandomInstance()" works either as
    "Point.newRandomInstance()" or as
    "newRandomInstance()", however. Why does this
    controversy exist?No controversy! Your main() is contained within class Point and as such knows about everything that is declared in class Point() but nothing about what is in class Circle unless you tell it to look in class Circle.

  • Static abstract method equivalent?

    From the forum thread:
    http://forum.java.sun.com/thread.jspa?forumID=31&threadID=5202376
    baftos wrote:
    On the othe hand OP had a legitimate desire.
    How can a superclass force its subclasses to
    provide a certain class (as opposed to instance) behaviour?
    Do other languages provide something like this?I like to have a static abstract method in a super abstract class:
    public static abstract Behavior getClassMarker();And each sub concrete class should have:
    public static Behavior getClassMarker(){
      return new Behavior(-- parameters --);
    }Could we have an equivalent that current Java allows? Or, do we see some good news on the horizon?

    Normally you create an instance with the metadata for the type, which annotations let you do:package dog;
    abstract class Dog {
      abstract String getBark() ;
      Dog () {
        assert (getBreed() != null);
      DogBreed getBreed () { return getClass().getAnnotation(DogBreed.class); }
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    public @interface DogBreed {
      String genericBark () ;
      String name () ;
    @DogBreed(name="Bulldog", genericBark="GrrrGrrrGrrr")
    class Bulldog extends Dog {
      String getBark() {
        return "Grrr";
    @DogBreed(name="Pomeranian", genericBark="Pirrr")
    class Pomeranian extends Dog {
      String getBark() {
        return "Sausages";
    public class DogAnnotationTest {
      public static void main (String...args) {
        Pomeranian pomme = new Pomeranian();
        System.out.println("The generic bark of the " + pomme.getBreed().name() + " breed is "
              + Pomeranian.class.getAnnotation(DogBreed.class).genericBark() + " but our  pomme cries "
              + pomme.getBark() + " for a jerky, his favorite food");
    }The limitation is that you can only annotate with simple types, so you're stuck with the abstract factory pattern if you want the creation. Not that that's a bad thing, as it lets you create instances of classes which haven't been loaded yet.

  • What is a Factory method and when to use this concept?

    Could any one please describe what a factory method is and explain how I can use it by giving a simple example

    A Factory Method (sometimes called a "virtual constructor") is a way to avoid hard coding what class is instantiated. Consider:
    DataSource myDataSource = new DataSource();Now, if you want to use some other DataSource in your app, say, an XMLDataSource, then you get to change this code and all subsequent lines that use this, which can be a lot. If, however, you specified and interface for your DataSources, say, IDataSource, and you gave the DataSource class a static "create" method that would take some indication of what sort of DataSource to actually use, then you could write code like:
    IDataSource myDataSource = DataSource.create(dataSourceString);And be able to pass in a dataSourceString describing what DataSource you wanted to use - and not have to recompile. Check out the Java Design Patterns site ( http://www.patterndepot.com/put/8/JavaPatterns.htm )
    Make sense?
    Lee

  • Reflect public field from static Factory class

    Hi, i have a static factory(all public static fields and methods, and private constructor), and i want to reflect one of the public fields with reflection. eg.
    package pak;
    public class Factory{
    public static byte MYFIELD=0;
    //private cannot instantiate
    private Factory(){}
    I which to use reflection to do somethin like this in another class
    try {
    Class xClass= Class.forName("pak.Factory"); //getClass ref
    Object xInstance= xClass.newInstance(); //ERR**get Object to extract field Val
    //4 Field.getByte(Object)
    SPECIFIED_VAL = xClass.getField("MYFIELD").getByte(xInstance);
    } catch (ClassNotFoundException e) {
    e.prin...................
    However as the nature of the static factory, i can't instantiate it so can't use
    java.lang.reflect.Field.getByte(Object)
    what i need is something like
    java.lang.reflect.Field.getByte()
    ??Any ideas on how to over come this?

    To get a single "known" static field you would do:
    Class myClass = Class.forName("my.Class");
    Field myClassField = myClass.getField("myField");
    Object value = myField.get(null);if you want all the fields:
    Class myClass = Class.forName("my.Class");
    Field[] allClassFields = myClass.getFields();Check the API docs under java.lang.Class ;-)

  • Factory methods and downcasting

    I am having a class hierarchy and a factory method that creates the classes from this hierarchy. The factory method returns the root class of this hierarchy and every time I want to use a class specific method of one of the sub classes I will have to check the type of this class and cast to this class type. My question is now if there is a possibility to avoid the type checking and casting or if this is one of the few situations where type checking and casting is approriate. To illustrate the problem here is some code:
    class Factory {
      public static A create() {
        if (//someCondition)
           return new B();
        else
          return new C();
    abstract class A {
      public void commonMethod() {
        // do stuff
      public void polymorphicMethod();
    class B extends A {
      public void polymorphicMethod() {
        // do something
      public void specificBMethod() {
        // do stuff that only B can do
    class C extends A {
      public void polymorphicMethod() {
        // do some other thing
      public void specificCMethod() {
        // do stuff that only C can do
    }Now I run into a situation where I have to downcast to the correct type.
    class Worker {
      public void work() {
        A a = Factory.create();
        if (a instanceof B) {
          ( (B) a).specificBMethod();
        } else if (a instanceof C) {
          ( (C) a).specificCMethod();
        } else {
          // Error
    }I think this problem always arises if you have a factory method that returns a class at the top of the hierarchy or a interface but you can not put all the methods that a client wants to call in this common class or interface. Is there a better a way to do this or is this already a good solution?

    In my particular case I have an XML parser that
    parses messages. I implemented each different message
    type as a different class and the parser uses the
    factory to create new message objects. The parser
    then uses methods that are defined in the topmost
    Message class and in an interface to set the
    attributes of the object. Each message class
    overrides a "handleXMLElement" method defining how to
    deal with the message specific XML elements. So this
    is fine the parser is the client of the factory and
    he uses only methods that are defined in a common
    class and an interface.
    After a message has been read the message object is
    forwarded to a hierarchy of message handlers. Of
    course the message handlers know of the message class
    hierarchy and want to access all methods of each
    message object. But since the parser only knows about
    the interface and the common class, the message
    handlers will have to cast the message objects to the
    concrete types.If the message type that's passed in has its behavior in the common interface, why is there a need to cast?
    So the parser-factory relationship works well but the
    (nasty) casting arises due to the later message
    handling. Maybe your message handling needs redesign. Or perhaps a hierarchy of callback objects that let you customize that part that changes for each message.
    I also remembered why I implemented it this
    way. In the Desing Patterns book of Gamma et. al.
    the Chain of Responsibility pattern can be
    implemented this way using casts. So the solution
    can't be that bad at all, I guess.Don't take that as gospel. GoF isn't perfection. Patterns can be misapplied.
    @stefan: I can't pull all my methods from the
    subclasses in one upper class, because the methods
    are different and specialised for each sub class. I
    don't think that it is good when one sub class knows
    all the methods of all other sub classes.Maybe a callback object can help sort this out. I think you need a redesign to eliminate the casts. More thinking is required.
    %

  • What is a factory method? when to use this concept?

    Could any oneplease describe what a factory method is and explain how I can use it by giving a simple example?

    Instead of instantiating a class all over your program you do it in one method that's part of the class. This means the class gets control over the instantiating process, a factory.
    1. You can implement a dispose facility, that is giving back objects that can be reused (when the factory method is called an old object is returned if there is one in store, only if not a new one is instantiated).
    2. An abstract class can have a factory method that returns concrete classes on demand, like
    abstract class Hello {
       static newHello(int id) {  // factory method
          switch (id) {
          case 0: return new Hi();
          case 1: return new Howdy();
          return null;
    public class Hi extends Hello {
    public class Howdy extends Hello {

  • Singleton - Why have a factory method?

    Question:
    Why bother to have a factory method [represented by getServiceFacade() below] for a singleton? Accessing any of the static methods in the singleton causes class instantiation.
    In other words, what advantage is there to invoking a method with ServiceFacade.getServiceFacade().method() vs. ServiceFacade.method() ???
    public final class ServiceFacade
    private static ServiceFacade serviceFacade = new ServiceFacade();
    // Constructor for the ServiceFacade
    private ServiceFacade()
    Log.info("ServiceFacade.ServiceFacade(): enter");
    try
    initializeServices();
    catch (Exception e)
    Log.error("ServiceFacade.ServiceFacade() Exception: static class not initialized.");
    Log.info("ServiceFacade.ServiceFacade(): exit");
    //public static ServiceFacade getServiceFacade()
    // Log.info("ServiceFacade.getServiceFacade(): enter/exit");
    // return serviceFacade;
    private static synchronized void initializeServices()
    throws ValidationException, MarshalException, IOException
    // A bunch of stuff here ...

    The idea behind a Singleton is that it allows some in-memory caching of state, since once a Singleton is instantiated, it stays in memory (being self-referential) as long as the JVM runs. Generally, the only static method is the "getInstance" (or in your case "getServiceFacade").
    During the initialization, the Singleton factory will typically perform a lot of "expensive" operations (e.g. JNDI lookups, establishing connection pools, etc.) and then hold on to this information, so that it doesn't have to do it again, making all subsequent operations that much faster.

Maybe you are looking for

  • Error while using BCP

    I am trying to export the file using bcp and my error is C:\Users\rajesh>bcp Adventureworks.HumanResources.Department out c:\test\dept.txt -n -SLaasya -T SQLState = 37000, NativeError = 4060 Error = [Microsoft][SQL Server Native Client 11.0][SQL Serv

  • Is there a new driver needed to run Photoshop CC after installing Windows 8.1?

    Has anyone had trouble with downloading pictures to Bridge after installing Windows 8.1?

  • Calling SQL*Loader from Forms

    Hi, I was wondering if anyone has called SQL*Loader from Forms? What I am wanting to do is use Oracle Forms as the interface where you can specify a file that you can import into the database and it will use a set control file. Push the import button

  • Input level for narration

    hello, I don't seem to have any input level lights when adding narration. The lights show up for audio and soundtracks but not for narration. How can I fix this please??

  • Firewall Dropping Packets - %FW-6-DROP_PKT: Dropping tcp session X.X.X.X X.

    Hi, Can anyone explain this error and what is a stray Segment with the IP ident 46866. I can't seem to find this error on the Cisco web site the only bug appears to be to do with Zone firewalls. I have an 877 Router on a remote site configured with I