305

What's a "static factory" method?

Tim
  • 41,901
  • 18
  • 127
  • 145
freddiefujiwara
  • 57,041
  • 28
  • 76
  • 106
  • 3
    @ThangPham Jason Owen's answer is flawed because it purports to be talking about the Factory Method pattern, which is very different from the static factory method pattern that it actually does talk about. So, while it does a good job of answering the actual question, I don't think it could be accepted in its current state, because it brings in an unrelated pattern and increases the already incredibly common confusion about the difference between the two patterns. – Theodore Murdock Sep 17 '14 at 00:43
  • 1
    @CMCDragonkai I think dependency injection and static factory are different. Static factory may be required even in case of dependency injection for instantiating dependencies to be injected. – Karan Khanna Apr 18 '18 at 08:25

14 Answers14

521

The static factory method pattern is a way to encapsulate object creation. Without a factory method, you would simply call the class's constructor directly: Foo x = new Foo(). With this pattern, you would instead call the factory method: Foo x = Foo.create(). The constructors are marked private, so they cannot be called except from inside the class, and the factory method is marked as static so that it can be called without first having an object.

There are a few advantages to this pattern. One is that the factory can choose from many subclasses (or implementers of an interface) and return that. This way the caller can specify the behavior desired via parameters, without having to know or understand a potentially complex class hierarchy.

Another advantage is, as Matthew and James have pointed out, controlling access to a limited resource such as connections. This a way to implement pools of reusable objects - instead of building, using, and tearing down an object, if the construction and destruction are expensive processes it might make more sense to build them once and recycle them. The factory method can return an existing, unused instantiated object if it has one, or construct one if the object count is below some lower threshold, or throw an exception or return null if it's above the upper threshold.

As per the article on Wikipedia, multiple factory methods also allow different interpretations of similar argument types. Normally the constructor has the same name as the class, which means that you can only have one constructor with a given signature. Factories are not so constrained, which means you can have two different methods that accept the same argument types:

Coordinate c = Coordinate.createFromCartesian(double x, double y)

and

Coordinate c = Coordinate.createFromPolar(double distance, double angle)

This can also be used to improve readability, as Rasmus notes.

jaco0646
  • 15,303
  • 7
  • 59
  • 83
Jason Owen
  • 7,200
  • 3
  • 21
  • 25
  • 41
    Note that a static factory method is not the same as the Factory Method pattern from Design Patterns [Gamma95, p. 107]. The static factory method described in this item has no direct equivalent in Design Patterns. – Josh Sunshine Jan 14 '13 at 15:40
  • 1
    The payoff for me on this answer is the reference to poolable objects. This is EXACTLY how I'm using the factory method pattern. Factory methods are provided to help control an object's lifecycle: "create" either pulls an object from the pool or creates a new instance if the pool is empty, "destroy" returns it to the pool for future re-use. –  Jun 01 '13 at 13:10
  • 5
    You should really be using "static factory method pattern" wherever you say "factory method pattern" in this post, you're using the wrong term. Also, you're linking to the Wikipedia article on a different pattern than the pattern you're talking about. The Factory Method pattern should probably have been called the "Factory Interface" pattern, because it involves using several factory objects that implement a factory interface to enable a single algorithm to produce as well as work with instances of an interface, by accepting a factory object that can produce the specific desired subclass. – Theodore Murdock Sep 17 '14 at 00:38
  • 2
    Note that the constructor doesn't have to be private. A class could provide both public static factory methods and constructors. – Kevin Jan 07 '15 at 05:01
  • 1
    Please edit your answer as per the comments given by @josh-sunshine , theodore-murdock and emerald214. Otherwise it would be keep confusing beginners. Kindly avoid that. Thanks. – Snesh Mar 04 '16 at 15:22
  • The factory method pattern page on wikipedia has changed, probably for the reasons given in the comments above. The cartesian/polar example is now on http://en.wikipedia.org/wiki/Factory_(object-oriented_programming) – fgb May 21 '16 at 18:55
  • "This a way to implement pools of reusable objects" - it's not a good idea to put pools of objects in a static context. Because it's a static state and this fact can cause some issues. For example, you need to create another pool of objects. You can't just create another instance of it, because it's global, because it in the static context. – Sneg Aug 22 '19 at 17:34
  • Note that one disadvantage of using only static factory method to instantiate objects is that classes without public or protected constructors cannot be subclassed. – dbustosp Nov 02 '19 at 13:49
186

NOTE! "The static factory method is NOT the same as the Factory Method pattern" (c) Effective Java, Joshua Bloch.

Factory Method: "Define an interface for creating an object, but let the classes which implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses" (c) GoF.

"Static factory method is simply a static method that returns an instance of a class." (c) Effective Java, Joshua Bloch. Usually this method is inside a particular class.

The difference:

The key idea of static factory method is to gain control over object creation and delegate it from constructor to static method. The decision of object to be created is like in Abstract Factory made outside the method (in common case, but not always). While the key (!) idea of Factory Method is to delegate decision of what instance of class to create inside Factory Method. E.g. classic Singleton implementation is a special case of static factory method. Example of commonly used static factory methods:

  • valueOf
  • getInstance
  • newInstance
Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
Grygoriy Gonchar
  • 3,898
  • 1
  • 24
  • 16
  • Can you tell me difference between new A() and A.newInstance() ? and inside A.newInstance what should we do ? – Shen May 11 '18 at 15:47
  • @Shen generally when you have a static method like newInstance the constructor is private so you can't create object with new A(), in such case you make newInstance method static and public and return the new A() object with it. P.S. I know I am late in answering this. – Shubhankar Dimri Jul 14 '20 at 22:31
137

We avoid providing direct access to database connections because they're resource intensive. So we use a static factory method getDbConnection that creates a connection if we're below the limit. Otherwise, it tries to provide a "spare" connection, failing with an exception if there are none.

public class DbConnection{
   private static final int MAX_CONNS = 100;
   private static int totalConnections = 0;

   private static Set<DbConnection> availableConnections = new HashSet<DbConnection>();

   private DbConnection(){
     // ...
     totalConnections++;
   }

   public static DbConnection getDbConnection(){

     if(totalConnections < MAX_CONNS){
       return new DbConnection();

     }else if(availableConnections.size() > 0){
         DbConnection dbc = availableConnections.iterator().next();
         availableConnections.remove(dbc);
         return dbc;

     }else {
         throw new NoDbConnections();
     }
   }

   public static void returnDbConnection(DbConnection dbc){
     availableConnections.add(dbc);
     //...
   }
}
azro
  • 53,056
  • 7
  • 34
  • 70
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
74

Readability can be improved by static factory methods:

Compare

public class Foo{
  public Foo(boolean withBar){
    //...
  }
}

//...

// What exactly does this mean?
Foo foo = new Foo(true);
// You have to lookup the documentation to be sure.
// Even if you remember that the boolean has something to do with a Bar
// you might not remember whether it specified withBar or withoutBar.

to

public class Foo{
  public static Foo createWithBar(){
    //...
  }

  public static Foo createWithoutBar(){
    //...
  }
}

// ...

// This is much easier to read!
Foo foo = Foo.createWithBar();
Rasmus Faber
  • 48,631
  • 24
  • 141
  • 189
  • So I tried implementing you example but I'm not sure how this works. Ar the two methods createWithBar and createWithoutBar supposed to call 2 private constructors inside the Foo class? – Essej Aug 08 '16 at 09:10
  • @Baxtex: Yes. Each will call a private constructor. Perhaps just the same one: `private Foo(boolean withBar){/*..*/}` `public static Foo createWithBar(){return new Foo(true);}` `public static Foo createWithoutBar(){return new Foo(false);}` – Rasmus Faber Aug 08 '16 at 12:01
  • 1
    I think this is not "scale" very well. If you have three or more parameters, how you could use this idea and create a nice name for the method? – Dherik Nov 29 '16 at 14:26
  • 1
    @Dherik: Then you should probably use the builder pattern instead: new FooBuilder().withBar().withoutFoo().withBaz().build(); – Rasmus Faber Nov 29 '16 at 21:02
22
  • have names, unlike constructors, which can clarify code.
  • do not need to create a new object upon each invocation - objects can be cached and reused, if necessary.
  • can return a subtype of their return type - in particular, can return an object whose implementation class is unknown to the caller. This is a very valuable and widely used feature in many frameworks which use interfaces as the return type of static factory methods.

fromhttp://www.javapractices.com/topic/TopicAction.do?Id=21

cdeszaq
  • 30,869
  • 25
  • 117
  • 173
Bobby
  • 18,217
  • 15
  • 74
  • 89
20

It all boils down to maintainability. The best way to put this is whenever you use the new keyword to create an object, you're coupling the code that you're writing to an implementation.

The factory pattern lets you separate how you create an object from what you do with the object. When you create all of your objects using constructors, you are essentially hard-wiring the code that uses the object to that implementation. The code that uses your object is "dependent on" that object. This may not seem like a big deal on the surface, but when the object changes (think of changing the signature of the constructor, or subclassing the object) you have to go back and rewire things everywhere.

Today factories have largely been brushed aside in favor of using Dependency Injection because they require a lot of boiler-plate code that turns out to be a little hard to maintain itself. Dependency Injection is basically equivalent to factories but allows you to specify how your objects get wired together declaratively (through configuration or annotations).

cwash
  • 4,185
  • 5
  • 43
  • 53
17

If the constructor of a class is private then you cannot create an object for class from outside of it.

class Test{
 int x, y;
 private Test(){
  .......
  .......
  }
}

We cannot create an object for above class from outside of it. So you cannot access x, y from outside of the class. Then what is the use of this class?
Here is the Answer : FACTORY method.
Add the below method in above class

public static Test getObject(){
  return new Test();
}

So now you can create an object for this class from outside of it. Like the way...

Test t = Test.getObject();

Hence, a static method which returns the object of the class by executing its private constructor is called as FACTORY method
.

Santhosh
  • 4,956
  • 12
  • 62
  • 90
  • Hi @Santhosh I have a concerned is Why don't you let the private constructor is public? If you don't want to create subclass it's fine for me, but If I don't intend to make private constructor do we have any benefit of `Static Factory Method` over public constructor? – Shen Nov 25 '18 at 09:29
  • I think it's seem like: `public static final Test Instance = new Test();` And you can get object by: `Test.Instance.getObject();` – SangLe Nov 04 '22 at 03:28
10

I thought i will add some light to this post on what i know. We used this technique extensively in our recent android project. Instead of creating objects using new operator you can also use static method to instantiate a class. Code listing:

//instantiating a class using constructor
Vinoth vin = new Vinoth(); 

//instantiating the class using static method
Class Vinoth{
  private Vinoth(){
  }
  // factory method to instantiate the class
  public static Vinoth getInstance(){
    if(someCondition)
        return new Vinoth();
  }
}

Static methods support conditional object creation: Each time you invoke a constructor an object will get created but you might not want that. suppose you want to check some condition only then you want to create a new object.You would not be creating a new instance of Vinoth each time, unless your condition is satisfied.

Another example taken from Effective Java.

public static Boolean valueOf(boolean b) {
        return (b ? TRUE : FALSE);
}

This method translates a boolean primitive value into a Boolean object reference. The Boolean.valueOf(boolean) method illustrates us, it never creates an object. The ability of static factory methods to return the same object from repeated invocations allows classes to maintain strict control over what instances exist at any time.

Static factory methods is that, unlike constructors, they can return an object of any subtype of their return type. One application of this flexibility is that an API can return objects without making their classes public. Hiding implementation classes in this fashion leads to a very compact API.

Calendar.getInstance() is a great example for the above, It creates depending on the locale a BuddhistCalendar, JapaneseImperialCalendar or by default one Georgian.

Another example which i could think is Singleton pattern, where you make your constructors private create an own getInstance method where you make sure, that there is always just one instance available.

public class Singleton{
    //initailzed during class loading
    private static final Singleton INSTANCE = new Singleton();

    //to prevent creating another instance of Singleton
    private Singleton(){}

    public static Singleton getSingleton(){
        return INSTANCE;
    }
}
Thalaivar
  • 23,282
  • 5
  • 60
  • 71
4

One of the advantages that stems from Static factory is that that API can return objects without making their classes public. This lead to very compact API. In java this is achieved by Collections class which hides around 32 classes which makes it collection API very compact.

Rakesh Chauhan
  • 413
  • 4
  • 7
4

One of the advantages of the static factory methods with private constructor(object creation must have been restricted for external classes to ensure instances are not created externally) is that you can create instance-controlled classes. And instance-controlled classes guarantee that no two equal distinct instances exist(a.equals(b) if and only if a==b) during your program is running that means you can check equality of objects with == operator instead of equals method, according to Effective java.

The ability of static factory methods to return the same object from repeated invocations allows classes to maintain strict control over what instances exist at any time. Classes that do this are said to be instance-controlled. There are several reasons to write instance-controlled classes. Instance control allows a class to guarantee that it is a singleton (Item 3) or noninstantiable (Item 4). Also, it allows an immutable class (Item 15) to make the guarantee that no two equal instances exist: a.equals(b) if and only if a==b. If a class makes this guarantee, then its clients can use the == operator instead of the equals(Object) method, which may result in improved performance. Enum types (Item 30) provide this guarantee.

From Effective Java, Joshua Bloch(Item 1,page 6)

SherlockHomeless
  • 153
  • 2
  • 10
4

A factory method a method that 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.

This is useful when working with hierarchies of related classes, a good example of this would be a GUI toolkit. You could simply hard-code calls to the constructors for concrete implementations of each widget but if you ever wanted to swap one toolkit for another you'd have a lot of places to change. By using a factory you reduce the amount of code you would need to change.

Bryan Kyle
  • 13,361
  • 4
  • 40
  • 45
  • Assuming you have your factory return an interface type, and not the concrete class that you are dealing with. – Bill Lynch May 30 '09 at 05:28
  • 1
    This answer is about the [factory method design pattern](http://en.wikipedia.org/wiki/Factory_method_pattern) not static factory methods. A static factory methods is simply a public static method that returns an instance of a class. See Chapter 2 of Effective Java for further detail. – Josh Sunshine Jan 14 '13 at 15:38
2

Java implementation contains utilities classes java.util.Arrays and java.util.Collections both of them contains static factory methods, examples of it and how to use :

Also java.lang.String class have such static factory methods:

  • String.format(...), String.valueOf(..), String.copyValueOf(...)
Volodymyr Dvornyk
  • 1,332
  • 1
  • 12
  • 15
2

A static factory method is good when you want to ensure that only one single instance is going to return the concrete class to be used.

For example, in a database connection class, you may want to have only one class create the database connection, so that if you decide to switch from Mysql to Oracle you can just change the logic in one class, and the rest of the application will use the new connection.

If you want to implement database pooling, then that would also be done without affecting the rest of the application.

It protects the rest of the application from changes that you may make to the factory, which is the purpose.

The reason for it to be static is if you want to keep track of some limited resource (number of socket connections or file handles) then this class can keep track of how many have been passed out and returned, so you don't exhaust the limited resource.

James Black
  • 41,583
  • 10
  • 86
  • 166
1

static

A member declared with the keyword 'static'.

factory methods

Methods that create and return new objects.

in Java

The programming language is relevant to the meaning of 'static' but not to the definition of 'factory'.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • @Victor Responses don't need to contain arguments. Facts should be sufficient: if controversial, they can be supported by argument or citation. I'm not aware there is anything controversial here. – user207421 Jun 09 '14 at 02:39
  • I stated that because the answer was too short and really don't understood well at first, second and third look, anyway is up to the OP to re ask. Nevermind, i have changed my mind and try to remove the downvote, but i can't. – Victor Jun 09 '14 at 14:49
  • @Victor Define 'too short'. Sometimes the real answer is just 'yes', 'no', 'neither', or 'both'. 'Too short' is entirely subjective. I still don't understand your original comment. You don't need arguments to support definitions. By definition. I've edited my answer so it would now be possible to remove the downvote. – user207421 Aug 11 '14 at 01:16
  • Of course is subjective... all stackoverflow answer are subjective, in fact they are related to the author level's of knowledge and will to answer. I really don't understand your answer, perhaps was to short. – Victor Aug 12 '14 at 15:07
  • @Victor Rubbish. Matters of fact are not subjective, and neither are matters that can be derived inferentially from facts or axioms. 'Too short' on the other hand is subjective, and I have already addressed it. This answer is essentially the same as [this one](http://stackoverflow.com/a/929203/207421), which you haven't commented on. Your comments remain obscure. – user207421 May 19 '15 at 09:54
  • i just want a more self explanatory answer... if you fell that your answer is good, go ahead, is good for me. The other answer that you point, has the same mistake, is too short, on my humble point of view... – Victor May 19 '15 at 15:10
  • @Victor You still haven't provided the definition of 'too short' that was requested, nor provided any argument to back up your comment, as also requested. Your comment therefore suffers from exactly the same faults you're accusing me of. – user207421 Sep 30 '15 at 13:02
  • You just mention the words and their correspondent definition separately. I guess that if you articulate the meaning of those words (static factory methods) in one sentence would be more explanatory. You just define "static", then "factory methods"... and leave the OP to his luck. You know, if you feel the answer is right is okey, i don't wanna to argue. Anyway... let's remove my down-vote. – Victor Sep 30 '15 at 22:02