What are static factory methods? - java

What's a "static factory" method?

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.

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

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);
//...
}
}

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();

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

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).

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.

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;
}
}

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.

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.

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)

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.

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 :
Arrays.asList("1","2","3")
Collections.synchronizedList(..), Collections.emptyList(), Collections.unmodifiableList(...) (Only some examples, could check javadocs for mor methods examples https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html)
Also java.lang.String class have such static factory methods:
String.format(...), String.valueOf(..), String.copyValueOf(...)

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'.

Related

Is there an elegant way to change what methods/variables an object of a class can use based on the constructor used to create this object?

So for example, when the object is constructed with lets say a constructor without arguments, this object is able/"allowed" to use a certain subset of the methods defined in the class, and when the object is created with a different constructor (for example with arguments) it is able/"allowed" to use a different subset of the methods defined in the class.
These are the conceptual solutions that spring to mind:
Use reflection in the constructors to modify the visibility/accessibility of its class methods. (Problem with this is EURGH... reflection)
Set boolean flags like isAllowedToUseMethodA in the constructor to identify which methods the object will be allowed to use. (Problem with this is the overhead the boolean checks will impose and also methods which are flagged as inaccessible will still be visible to the object and can be attempted to execute)
The obvious elephant in the room answer to this is "Make 2 different classes." and I understand that, I'm just curious is there an elegant way to do this if I want to do this in a single class?
Both options 1 and 2 have a multitude of problems, however fortunately there is a simple and reasonably elegant way to do exactly what you want:
Use inheritance.
Define different versions of the object all inheriting off a common (potentially abstract) core.
Then have factory methods that construct the correct version of each one depending on which factory method you call.
You can't actually use a different subset of methods, but you can kind of 'switch' by means of the strategy pattern.
E.g. for your constructors you set different strategies:
public class XXX() {
method1Strategy = new method1Strategy1();
method2Strategy = new method2Strategy1();
}
public class XXX( ... ) {
method1Strategy = new method1Strategy2();
method2Strategy = new method2Strategy2();
}
And in your methods you execute the concrete strategy:
public Object method1(...) {
return method1Strategy.execute(...)
}
public Object method2(...) {
return method2Strategy.execute(...)
}

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?
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:
Consider static factory methods instead of constructors - Josh Bloch
What are static factory methods in Java?
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.
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.
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.

Why some classes don't need the word "New" when creating its instance?

I am new to Java. One thing confuses me is to why some of the classes need new to instantiate, and why some others do NOT need new to instantiate.
For example, I am looking at log4j, it does not need new.
// get a logger instance named "com.foo"
Logger logger = Logger.getLogger("com.foo");
logger.setLevel(Level.INFO);
Why do some other classes need new? For example, an Employee class:
Employee X = new Employee (John);
X.getwork();
etc etc.
Why we did not say , Logger logger = new Logger(...);? and why were we able to use it even without new, like logger.setLevel(), etc.
The only way to create a new object in Java is with new [1]. However, in some classes, you're not permitted to say new for yourself, you must call a factory method, which might be static (as with your logger example) or not. The author of a class sets this up by making the constructor(s) have access other than public.
Also note that your example may not involve a new object at all. That Logger function might be returning an old object, not a new one.
The following poem by Ogden Nash seems faintly relevant:
This morning I went to the zoo
In order to look at the gnu.
But the old gnu was dead,
and the new gnu, they said,
Was too new a new gnu to view.
[1] Unless you get involved in low-level reflection, or use Object.clone()
In this case, we are dealing with factory methods, as I stated in my comment.
See the relevant API specification on Logger
Retrieve a logger named according to the value of the name parameter. If the named logger already exists, then the existing instance will be returned. Otherwise, a new instance is created.
By default, loggers do not have a set level but inherit it from their neareast ancestor with a set level. This is one of the central features of log4j.
The factory method pattern is a creational design pattern, and, according to Wikipedia, is often useful in the following situations:
The factory pattern can be used when:
The creation of an object precludes its reuse without significant duplication of code.
The creation of an object requires access to information or resources that should not be contained within the composing class.
The lifetime management of the generated objects must be centralized to ensure a consistent behavior within the application.
All three of these are applicable here... who knows what kind of work goes into finding the correct logger? You're not really interested in creating a brand new logger each time you want to use one... instead, your focus is mainly just that -- to use one.
The Creative Commons Wiki also has a relevant article,
Factory methods are sometimes used in place of constructors for any of several reasons:
Some languages (such as Java) do not allow constructors to have useful names
Some languages (such as Java) do not allow constructors to have different names (which may be necessary if you want to use the same method signature for two constructors)
To allow the same instance to be reused instead of recreated each time it is needed (see FlyweightPattern)
I think the third option is probably the most applicable here. Using manual creation of a new Logger, you are unable to adequately share them. Using the getLogger facade enables this to happen transparently.
All in all, the use of factory methods is usually to enable cleaner more straight-forward code without exposing work you don't necessarily care about.
For instance, some classes may prevent you from creating more than one object in the application. It that case you need to call some method for instantiate the class, like the Logger.getLogger(). The getLogger() may have the code like this:
if(uniqueInstance == null) {
uniqueInstance = new Logger();
}
return uniqueInstance;
Where uniqueInstance is an instance of Logger. This is a design pattern called Singleton. In this pattern, you can't instantiate the class because it's constructor is private.
Some other way that you can't instantiate a class is when the class is defined as static.
Classes that have public constructors and aren't static need to be instantiated with the new keyword.
because Logger.getLogger() returns a Logger object. new Logger() calls the constructor which also returns a Logger. This also kind of uses new too, because inside the Logger class is probably something like:
public class Logger {
public static Logger getLogger() {
return new Logger("foo", "bar");
}
}
Well what you are asking is more related to design patterns. The Logger class is following singleton pattern.
Suppose you want that only a single instance of your class gets created accross the application then you can make your constructor private and provide a static method which creates and stores the object of your class when invoked for the first time.
public class SingletonPattern{
private static SingletonPattern instance;
private SingletonPattern(){}
public static synchronized SingletonPattern getInstance(){
if (instance == null){
instance = new SingletonPattern();
}
return instance;
}
}
In this way you can restrict your class to be instantiated only once.
In your example you have to different use cases : the static method that returns an object and the actual constructor call.
The static method is a method that doesn't need to be call on a object, here it's inner mechanism may instantiate an object and return it for futur usage, in this method, there's a call to "new" but the object might be configured, or retrieved from a cache before being return. This is this kind of call
Logger logger = Logger.getLogger("com.foo");
The actual constructor call (which use new) is the normal way to create new object.
You were not technically using the Logger class, but were using a method. You were not technically instantiating the Logger class, nor keeping a reference to it directly as you would with Logger logger = new Logger(). Instead, what you are doing is accessing a method to get back a returned instance. It would be nice to see the class definition. However, more than likely what you have is a static method inside of the class. And the class is more than likely defined with a private constructor. This allows the methods to be accessed without instantiating the class. You can see a good explanation of this, and of static in java here: https://stackoverflow.com/a/1844388/1026459
Some classes cannot be instantiated outside of themselves (e.g. the Math class, these classes have non-public constructors). Of those classes, some provide methods that return instances of the class (e.g. the InetAddress class). These are called factory methods. They are static methods that return instances of the class they're in, so the new keyword need not be used (it is instead used inside of the factory methods). For example:
public class A {
private A() {}
public A createAnA() { return new A(); }
}
Here, createAnA() is the factory method.

How to enforce certain methods of Object creation?

I'm working with an abstract class and a (growing) set of subclasses of this class. For certain reasons all subclasses of A should implement the singleton pattern. During startup of the application there exists a List<Class<? extends A>> and I would like to initialize all singleton-instances.
From what I see, my option here is to go for Reflection, enforcing by guidelines that all A-implementing classes have to have a defined constructor and invoke that via o.getDeclaredConstructor().newInstance();.
I've also tried a different approach where I used overloading of static methods. That is, A defined a static initialize method and all subclasses had to reimplement that method. The call can again be invoked via reflection.
The first approaches has the obvious disadvantage that violations of the programming-guideline result only in runtime-errors, not in compile-time errors. The second is even worse, if a subclass does not implement the static method, only the method in A is called with no apparent exception thrown.
So: How do I enforce a uniform way to initialize in a set of singleton classes?
Edit:
A configuration-class generates a list of all children of A during startup, those classes can be either registered directly in the configuration class programmatically or configured via a configurationfile:
private void initModules() {
Configurator.addModule("modulename", SubOfA.class);
...
}
private void initModuleFile() {
...
String name = in.readLine();
String classname = ...;
String modulename = ...;
Configurator.addModule(modulename, Class.forName(classname));
}
those classes can be [...] configured via a configurationfile
In this case the common approach is like your first proposal: Class.forName("...").newInstance()
(This can, of course, be encapsulated by some kind of factory pattern.)
Since, in Java, you cannot enforce a particular constructor to be implemented by subclasses, the only viable way is to demand a default constructor by design guidelines/contracts.
As an example, have a look at Android's Parcelable:
Classes implementing the Parcelable interface must also have a static
field called CREATOR, which is an object implementing the
Parcelable.Creator interface.

instance factory methods Vs Static factory methods

Can't all factory methods be static ? Does something that produces a product need state ? When is it appropriate to go for a instance factory or static factory method ? Can you provide me examples differentiating the two ?
Assuming that by "instance factory method" you're actually saying about the GoF "factory method", the term "static factory method" is described by Joshua Bloch in his book "Effective Java". Googling around I reached at these sites:
Factory Method: http://sourcemaking.com/design_patterns/factory_method
Static Factory Method: http://www.informit.com/articles/article.aspx?p=1216151
Hope that it helped to make the difference a little bit clearer.
Following Marvo's advice:
Factory Method as stated in GoF:
define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Example (Java code):
public abstract class Product { ... }
public class ConcreteProduct extends Product { ... }
public abstract class Creator {
public void anOperation() { ... product = factoryMethod(); ... }
public abstract Product factoryMethod();
}
public class ConcreteCreator extends Creator {
public Product factoryMethod() { return new ConcreteProduct(); }
}
Static Factory Method as stated in Effective Java:
A class can provide a public static factory method, which is simply a static method that returns an instance of the class. (...) One advantage of static factory methods is that, unlike constructors, they have names. (...) A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they’re invoked. (...) A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type. (...) The main disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed.
Example (Java code):
public class Boolean {
...
public static Boolean valueOf(boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE;
}
...
}
My current preference is to make factory methods not static for the sake of easier testing. You can't change a static factory method call at runtime, whereas if I could provide a factory implementation to the object then I could test it more thoroughly as I'm in more control of the context and object graph.
If you are returning a Singleton from your factory then you are going to need make sure you only have one instance, if you are going to create a new instance every time you call the factory then make it static.
It depends, for instance you can have a factory that will only produce a certain amount of objects in which case there will be an associated state. For the most part factory methods can be static as long as they don't rely on any non-static variables (such as non-static globals and such) for their creation. It also tends to differentiate different factories for different parts of an application so depending on whether there is a state or not in your factory is what you would go with it's not set in stone that all factory methods should be static, check what situation applies to you and write it appropriately.
Another consideration is the static keyword, this causes whatever is static to be instantiated only once in memory but a drawback is that it resides in the process memory always (which increases working set size). This may be something that you don't want as your factory might have very high locality in certain areas and it would otherwise just be using up memory somewhere else but this is usually an optimization issue that should be looked at only if the issue of memory pressure in your application arises.
If instances are needed before, then you can use static factory, otherwise instantiate the factory itself and pass it to your code.

Categories

Resources