tags:

views:

87

answers:

4
class XFactory {

  private XFactory() {}

  static void getX() {
    if(...)
      return new A(new XFactory());
    else
      return new B(new XFactory());
  }

}

class A {
   private A() {}
   public A(XFactory xf) {}
}

class B {
   private B() {}
   public A(XFactory xf) {}
}

By this way I can ensure only Factory can create instances of it's belonging Classes.

Is this right approach or there is any other alternative/good approach?

+2  A: 

The common approach (in C++) is to make the "belonging classes" constructors private, and have them declare the factory class as friend.

Alex Martelli
+1  A: 

I would make classes A and B friends of XFactory, and keep all their constructors private. Therefore, only XFactory has access to their constructors.

That is, in C++. In Java or C#, I don't see any clean way of enforcing that at compile-time. Your example is far from fool-proof and even a bit confusing, since as long as one has an instance of XFactory, he can pass it to the constructor of A or B and instantiate them directly like that.

Dr_Asik
no one can create instance of XFactory. bcoz its constructor is private.
Prabu
+1  A: 

If you were up for hacks and could not make your constructors private, you could: Make your factory a global singleton and to create an object:

  • Create a random key
  • Add that key to a private list in the factory object of keys in use
  • Pass the key to the constructor
  • Have the constructor retrieve the global factory object and call it to validate the key.
  • If they key validation fails, scuttle your program (call exit, die, ... whatever is appropriate). Or possibly email a stack tract to an admin. This is the kind of thing that should be caught quickly.

(Do I get hack points?) Jacob

TheJacobTaylor
A: 

In Java you can make the constructors private and provide the factory in the form of a public nested class, since nested classes have access to the private members of the class in which they are declared.

public class ExampleClass {

    private ExampleClass() {

    }

    public class NestedFactory {
        public ExampleClass createExample() {
            return new ExampleClass();
    }
}

Anyone who wanted to could create an instance of ExampleClass.NestedFactory and through it instantiate ExampleClasses.

I haven't been able to figure out a way to do this that lets you then inherit from ExampleClass since the Java compiler demands that you specify a constructor for the superclass... so that's a disadvantage.

KidDaedalus