wrahool
wrahool

Reputation: 1141

How does a static factory method return a new instance?

I've been reading in various places that it's often advisable to use static factory methods over public constructors.

One of the advantages is that unlike with constructors, a static factory method does not create a new object each time it is invoked. However, as I read on this site, the factory method for the class

class Employee {
   private int _type;
   static final int ENGINEER = 0;
   static final int SALESMAN = 1;
   static final int MANAGER = 2;

   Employee (int type) {
       _type = type;
   }
}

is defined as :

static Employee create(int type) {
     return new Employee(type);
 }

Thus to create a new instance, we do

Employee eng = Employee.create(Employee.ENGINEER);

What I don't understand is, isn't the factory method invoking the public constructor? So isn't it creating a new instance all over again?

A second aspect of using static factory methods that I don't quite understand is why can classes without public / protected constructors not be subclassed?

Upvotes: 2

Views: 10607

Answers (4)

Raji
Raji

Reputation: 527

I've been reading in various places that it's often advisable to use static factory methods over public constructors.

Actually I don't think this is true or advisable to do this. The factory pattern has it's own uses and CANNOT replace the functionality provided by public constructors. "public constructors" ARE PROVIDED to dictate how other classes will create your class. It makes no sense adding a simple wrapper static function which does nothing else other than accept the same parameters as the constructor and create the object as shown in the code. Doing this is a MISUSE of the factory pattern.

"Factory pattern" is a creation pattern that is needed ONLY IF there is a need for an INSTANTIATION LOGIC of different classes based on input parameters. In your eg., if Engineer, Salesman and Manager were different classes derived from the same Employee class, and based on the type the appropriate class is constructed, then a factory is needed.

Design can be done in anticipation of a required functionality, BUT, I think, it is much better to just design for the functionality at hand and modify it when the need arises.

Upvotes: 0

Stephen C
Stephen C

Reputation: 719289

One of the advantages is that unlike with constructors, a static factory method does not create a new object each time it is invoked.

Actually, that would be better stated as "a static factory method does not necessarily create a new object each time it is invoked". And that effectively addresses your first query. (In your example, it does create a new instance each time ... but that's not the only reason to use static factory methods.)

A second aspect of using static factory methods that I don't quite understand is why can classes without public / protected constructors not be subclassed?

This is actually orthogonal to the issue of factory methods. (And also not completely true, either.)

You cannot subclass a class that has no accessible constructor because the JLS requires that every constructor for a subclass explicitly or implicitly invokes a superclass constructor. If no superclass constructors are accessible to the subclass, then this requirement cannot be met.


In fact, there is another reason. for using static factory methods instead of invoking constructors directly. A static factory method can create and return instances of different classes. For example:

  // static factory method ...
  public static CharSequence createCharSequence(char[] chars, boolean mutable) {
      return mutable ? new StringBuilder(chars) : new String(chars);
  }

And indeed you can take this further with non-static factory methods and factory objects. These allow you to (respectively) inherit and override object creation logic, and separate the object creation logic from the object classes themselves.

Upvotes: 1

AllTooSir
AllTooSir

Reputation: 49402

I believe it was not implemented correctly . Shouldn't the constructor be private in this case ? The whole point of having a static factory method is to bar direct access to create instances using the constructor directly from other code. Say suppose , your class provides DB connection , as we know connections are resource intensive and we shouldn't create connections indiscriminately , a static factory is used to request connection object . The factory method checks to see if there is a free connection object in the pool and returns it . Re-usablity is important concept here , which is implemented by static factory method.

Another point is that it abstracts away the instantiation of an object. Generally factories are useful when you know that you need a new instance of a class that implements some interface but you don't know the implementing class.

The code provided in that link is just a sample of how it works , though , not a good example . Read further :

The most obvious motivation for Replace Constructor with Factory Method comes with replacing a type code with subclassing. You have an object that often is created with a type code but now needs subclasses. The exact subclass is based on the type code. However, constructors can only return an instance of the object that is asked for. So you need to replace the constructor with a factory method.

Coming back to your questions:

What I don't understand is, isn't the factory method invoking the public constructor? So isn't it creating a new instance all over again?

Yes probably it shouldn't .

I don't quite understand is why can classes without public / protected constructors not be subclassed?

Even a constructor with default access , i.e. with no access modifier can be sub classed . But the sub class should be part of the package . Remember once you sub class a class , while creating objects of the sub class , the sub class constructor implicitly/explicitly has to invoke the super class constructor. Now if the super class constructor is inaccessible from the sub class constructor because it is marked as private , then the instantiation fails . Hence the subclassing has no meaning.

Suggested Reading:

  1. Consider static factory methods instead of constructors - Josh Bloch
  2. What are static factory methods in Java?

Upvotes: 4

bNd
bNd

Reputation: 7640

isn't the factory method invoking the public constructor? So isn't it creating a new instance all over again?

Yes, It allows to create new object so make private constructor.

And create create method inside class.

Try with

 public class Employee {
         private int _type;
           static final int ENGINEER = 0;
           static final int SALESMAN = 1;
           static final int MANAGER = 2;
         public static   Employee INSTANCE;
         public static final Employee create(int type)
         {
           if(INSTANCE==null)
           {
               INSTANCE=new Employee(type);
           }
           return INSTANCE;
         }
           private Employee (int type) {
               _type = type;
           }
    }

new object is created through clone also. you can override the Object class's clone() method to throw the CloneNotSupportedException exception.

Upvotes: 0

Related Questions