This might just be a question of personal taste and workflow, but in case it's more than that, I feel I should ask anyway.
In Java, what differences are there between creating an instance via constructor and via a static method (which returns the instance)? For example, take this bit of code from a project I'm working on (written up by hand at time of posting, so some shortcuts and liberties are taken):
Plugin main;
Map<int, int> map;
public Handler(Plugin main) {
this.main = main;
}
public static Handler init(Plugin main) {
Handler handler = new Handler(main);
handler.createMap();
}
public void createMap() {
this.map = Maps.newHashMap();
}
In cases like this, what would the difference be between using
Handler handler = new Handler(this);
and
Handler handler = Handler.init(this);
in the Plugin class, besides the fact that createMap() runs only in the latter because it's not called in the constructor?
To clarify, in this case, Plugin is considered the main class.
I know enough Java syntax to be able to write intermediate-level plugins, but not enough about Java itself to know the difference between these two ways of doing this.
EDIT: For instance, the Maps class that I used to create the Map uses a static factory method (I hope I'm using that term correctly) called using the class instead of an object.
There are both advantages and disadvantages of static factory methods.
Advantages
Descriptive, meaningful names.
When invoked they can decide whether to return a new instance
They can return an object of any subtype of the return type
They reduce the verbosity of creating parameterized type instances
Disadvantages
If you provide only static factory methods, classes without public or protected constructors cannot be subclassed
They are not readily distinguishable from other static methods
Source: Effective Java, Second Ed.
The difference is a static factory method is more flexible. It can have all sorts of ways to return an instance. It can do other side stuff. It can have a more descriptive name. It can be invoked by its simple name (e.g. foo(args)) by static import or inheritance.
The constructor call is more certain - the caller knows exactly what's happening - a new instance of that exact class is created.
Related
Curiousity made me ask this question. I'd like to know what is better to use to instantiate a class.
I could either do this with a constructor:
public ExampleClass(someParameters){}
, or I could do this with a public static method:
public static ExampleClass getInstance(someParameters){return new ExampleClass}
Personally I do like to use static methods to instantiate a class because it looks cleaner to instantiate a class that way. However, I would really appreciate some supported opinions on this because I'm just a hobbyist that would like to code more professionally-looking.
so your question is should you use static factory methods? Well use them when they are appropriate. For example they can have a name like of or create, etc. So they can be named (unlike constructors that must have the same name as the class).
Then you can return a subtype, or cache an object - you can't do that with a plain constructor.
From the Effective Java book, Joshua Block contests that it is better to have static factory methods for object creation than plain old constructors. Advantages include
Unlike constructors, they have names
Unlike constructors, they do not require to create a new object each time they’re invoked
Unlike constructors, they can return an object of any subtype of their
return type
They reduce verbosity of creating parameterized type instances
Disadvantages:
They cannot be used in subclasses construction
They are not readily distinguishable from other static 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.
Can somebody explain to me why classes are not first class objects in Java? There are certain patterns that would work really well if it did and I'm constantly writing factory classes with getters and setters and just adding unnecessary cruft to classes just so I can get around to passing instances to methods instead of actual classes to factor out generic bits of code. For example:
public class AsyncBookSearch extends AsyncTask<String,BookItem,Void> {
public ListView list;
public AmazonItemAdapter<BookItem> adapter;
public AsyncBookSearch(ListView l,AmazonItemAdapter<BookItem> ad) {
list = l;
adapter = ad;
}
#Override
protected Void doInBackground(String... keywords) {
// TODO Auto-generated method stub
new BookSearch(keywords[0],list,adapter).parse();
return null;
}
}
I have several such classes and if I want to make the whole thing generic then the stuff in doInBackground() will lead to several extra methods and other kinds of duplication in argument passing which wouldn't be a problem if I could write the following:
public class AsyncItemSearch<T extends GenericItemSearch<S>,S extends GenericItem> extends AsyncTask<String,T,Void> {
public ListView list;
public AmazonItemAdapter<S> adapter;
public AsyncBookSearch(ListView l,AmazonItemAdapter<S> ad) {
list = l;
adapter = ad;
}
#Override
protected Void doInBackground(String... keywords) {
// TODO Auto-generated method stub
new T(keywords[0],list,adapter).parse();
return null;
}
}
Currently I can't write code like that in Java. I have to introduce unnecessary coupling into pretty much every class involved and this just makes things more convoluted because now not only does each instance need to worry about it's own state but also about state in objects completely unrelated to it's task.
I don't think your question is really about Classes being "first class" objects. I suspect it really has to do with how java handles generics.
I think you need to understand type erasure: in your example you essentially want to write something like
void foo<T>{
T bar = new T();
}
but this is not possible, because at run time, there is no information about what class T actually is, due to type erasure:
When a generic type is instantiated,
the compiler translates those types by
a technique called type erasure — a
process where the compiler removes all
information related to type parameters
and type arguments within a class or
method. Type erasure enables Java
applications that use generics to
maintain binary compatibility with
Java libraries and applications that
were created before generics.
Classes are first class. They are objects of the class Class. They can be assigned to variables and fields, passed as arguments, and even created dynamically.
The problem you are having is generic types are not reified, they are only visible at compile time. Additionally, because constructors are not inherited, unless you know exactly which class you want to create, you can't know if the constructor with the desired arguments exists. One way to work around the problem you are having is to pass in a factory class.
public class AsyncItemSearch<T extends GenericItemSearch<S>,S extends GenericItem> extends AsyncTask<String,T,Void> {
public ListView list;
public AmazonItemAdapter<S> adapter;
public GenericItemSearchFactory<T> factory;
public AsyncBookSearch(ListView l,AmazonItemAdapter<S> ad, GenericItemSearchFactory<T> factory) {
list = l;
adapter = ad;
this.factory = factory;
}
#Override
protected Void doInBackground(String... keywords) {
this.factory.getInstance(keywords[0],list,adapter).parse();
return null;
}
}
Classes ARE first class objects in Java (of class Class). You can assign them to variables, pass around, return from function etc. I think you meant to ask some other question, but I am not sure what that question could be. Maybe something about erasure versus reification of generic types? An answer to that might be interesting.
An example of the cruft you keep writing could help.
Also, consider the difference between question like 'does X have a reason' and 'does X have good uses'.
EDIT: (answering the comment: "I have not seen a single example of classes being passed around" (btw: I still thing it's a question about erasure versus reification, but this specific comment does not address it). I am surprised you have not. Passing classes in Java is very common. Few examples from really popular APIs that pop to my mind without thinking:
Hibernate / JPA entity manager looks up a mapped object on the basis of its class and its primary key; eg: Invoice i = entityManager.find(Invoice.class, 12l)
GWT uses a special factory to inject classes that only exist in generated javascript (or otherwise parametrized); The method takes an instance of class to create; eg: Resource res1 = GWT.create(MyResources.class);
Spring's ApplicationContext gives you beans based on the class you pass to getBean method; so you would do: DataSource default = applicationContext.getBean(DataSource.class);
Class instances are used in the rare cases when C# would use reflection (and Java cannot, as it erases generic types at runtime); the pattern is sometimes called a "class token"
In most of cases above you will see class literal (as a first-class objects classes do have literals in Java) and not a dynamic call, but that is mostly because of the static nature of the language (and of programmers that use it). It is usually considered a good thing to know your types at compile-time.
since Java does not support generics at runtime, you cannot create a generic class on-the-fly. Which makes no difference, since you can create a non-generic class and use it as a generic one.
Answering the other comment: creating and modifying classes at runtime is used commonly, but mainly by Java infrastructure: application servers, libraries. Look at JMockit. You can actually modify an existing class or replace its methods on-the-fly for a duration of a method call.
I would not consider classes to be first class object, instead I would say that Class is a part of the reflection API, since you can not use it as freely as in other, more dynamic languages. I.e. you can't create new instances without reflection.
The main reason is the meta model of java. You can't overwrite static methods, and a constructor that exists in a class does not necessarily exist in its subclasses. This is also the reason why your code new T(keywords[0],list,adapter) would not work, subclasses may not have such a constructor.
Thus, in java, there is no use for class objects since you definitely need reflection to check if you code is valid at runtime.
A different topic are generic type parameters. You can't do T.class because genrics are somehow a language hack in java (and nothing compared to C++ Templates). The main reason for this is compatibilty with older java versions.
However, you can workaround this using the reflection API mentioned above:
public Foo<T extends Bar> {
private Class<T> barClass;
public Foo(Class<T> barClass) {
this.barClass = barClass;
}
public T createSomeBar(String arg) {
try {
// the bar contract says that subclasses must have such a constructor
return barClass.getConstructor(String.class).newInstance(arg);
} catch ... // the contract was violated, do proper handling
}
}
Classes are first-class items. You can call the "newinstance" method on a class to create an instance, or you can ask for a constructor object and use that. Try this code:
public class AsyncItemSearch<T extends GenericItemSearch<S>,S extends GenericItem> extends AsyncTask<String,T,Void> {
private Constructor<T> searchConstructor;
public ListView list;
public AmazonItemAdapter<S> adapter;
public AsyncBookSearch(Class<T> theClass, ListView l,AmazonItemAdapter<S> ad) {
list = l;
adapter = ad;
searchConstructor = theClass.getConstructor(String.class, ListView.class, AmazonItemAdapter<S>.class);
}
#Override
protected Void doInBackground(String... keywords) {
// TODO Auto-generated method stub
searchConstructor.newInstance(keywords[0],list,adapter).parse();
return null;
}
}
Call it like so:
AmazonItemAdapter<Book> amazonAdapter = new AmazonBookAdapter();
AsyncItemSearch<BookSearch,Book> s =
new AsyncItemSearch<BookSearch,Book>(
BookSearch.class, myListView, amazonAdapter
);
s.doInBackground("have", "at", "thee", "!");
I just noticed this reference to first class generics in Java. Guy L. Steele and I wrote a paper in the 1998 OOPSLA Conference proposing a way to add support for first-class generics for Java that regrettably was not adopted by the committee at Sun Microsystems controlling the evolution of Java. See https://dl.acm.org/doi/abs/10.1145/286936.286958. My graduate students and I subsequently showed that this approach was comparable in efficiency to erasure (using Java JIT compiler technology that was not tuned to optimizing the idioms used in our implementation of Java generics). See https://www.semanticscholar.org/paper/Efficient-Implementation-of-Run-time-Generic-Types-Allen-Cartwright/cb07594f5e070e54ff891d064430c41f2091e2b4 and https://www.cs.rice.edu/~javaplt/papers/sac2006.pdf.
This question, like my previous question, references Effective Java. This time I have quite a few sub-questions.
A privileged client can invoke the private constructor reflectively with the aid of the AccessibleObject.setAccessible() method. If you need to defend against this, modify the constructor.
How, exactly, can a private constructor be invoked? And what is AccessibleObject.setAccessible()?
What approach do you experts follow with singletons?
// Approach A
public class Test{
public static final Test TestInstance = new Test();
private Test(){ ... }
.
.
.
}
// Approach B
public class Test{
private static final Test TestInstance = new Test();
private Test(){ ... }
public static Test getInstance() { return TestInstance; }
.
.
.
}
Isn't the second approach more flexible, in case we have to make a check for new instances every time or the same instance every time?
What if I try to clone the class/object?
a single-element enum type is the best way to implement a singleton.
Why? How?
A priviledged cleint can invoke the private constructor reflectively with the aid of the AccessibleObject.setAccessible method, If you need to defend this, modify the constructor. My question is: How exactly can a private constructor is invoked? and what is AccessibleObject.setAccessible??
Obviously a private constructor can be invoked by the class itself (e.g. from a static factory method). Reflectively, what Bloch is talking about is this:
import java.lang.reflect.Constructor;
public class PrivateInvoker {
public static void main(String[] args) throws Exception{
//compile error
// Private p = new Private();
//works fine
Constructor<?> con = Private.class.getDeclaredConstructors()[0];
con.setAccessible(true);
Private p = (Private) con.newInstance();
}
}
class Private {
private Private() {
System.out.println("Hello!");
}
}
2.What approach do you experts follow with singletons:
...
Typically, the first is favoured. The second (assuming you were to test if TestInstance is null before returning a new instance) gains lazy-loading at the cost of needing to be synchronized or being thread-unsafe.
I wrote the above when your second example didn't assign the instance to TestInstance at declaration. As stated now, the above consideration is irrelevant.
Isn't the second approach more flexible in case we have to make a check for new instance every time or same instance every time?
It's not about flexibility, it's about when the cost of creating the one (and only) instance is incurred. If you do option a) it's incurred at class loading time. That's typically fine since the class is only loaded once it's needed anyway.
I wrote the above when your second example didn't assign the instance to TestInstance at declaration. As stated now, in both cases the Singleton will be created at class load.
What if I try to clone the class/object?
A singleton should not allow cloning for obvious reasons. A CloneNotSupportedException should be thrown, and will be automatically unless you for some reason implement Cloneable.
a single-element enum type is the best way to implement a singleton. Why? and How?
Examples for this are in the book, as are justifications. What part didn't you understand?
Singletons are a good pattern to learn, especially as an introductory design pattern. Beware, however, that they often end up being one of the most over-used patterns. It's gotten to the point that some consider them an "anti-pattern". The best advice is to "use them wisely."
For a great introduction to this, and many other useful patterns (personally, I find Strategy, Observer, and Command to be far more useful than Singleton), check out Head First Design Patterns.
A priviledged cleint can invoke the private constructor reflectively with
the aid of the
AccessibleObject.setAccessible method,
If you need to defend this, modify the
constructor. My question is: How
exactly can a private constructor is
invoked? and what is
AccessibleObject.setAccessible??
You can use java reflection to call private constructors.
What approach do you experts follow with singletons:
I am a fan of using enum to actually do this. This is in the book also. If that's not an option, it is much simpler to do option a because you don't have to check or worry about instance being already created.
What if I try to clone the
class/object?
Not sure what you mean? do you mean clone() or something else that I don't know of?
a single-element enum type is the best way to implement a singleton.
Why? and How?
Ahh my own answer. haha. This is the best way because in this case, the java programming language guarantees a singleton instead of the developer having to check for a singleton. It's almost as if the singleton was part of the framework/language.
Edit:
I didn't see that it was a getter before. Updating my answer to this - it's better to use a function such getInstance because you can control what happens through a getter but you can't do the same if everybody is using a reference directly instead. Think of the future. If you ended up doing SomeClass.INTANCE and then later you wanted to make it lazy so it doesn't load right away then you would need change this everywhere that its being used.
The first rule of the Singleton (Anti-) Pattern is don't use it. The second rule is don't use it for the purpose of making it easy to get at a single instance of a class that you want multiple other objects to share, especially if it is a dependency of those classes. Use dependency injection instead. There are valid uses for Singletons, but people have a tendenecy to badly misuse them because they're so "easy" to use. They make it very difficult to test classes that depend on them and make systems inflexible.
As far as your questions, I think 1, 2 and 3 can all be answered by saying "use an enum-singleton". Then you don't need to worry about constructor accessiblity issues, clone()ing, etc. As far as 4, the above is a good argument for them. I also have to ask, did you read the section in Effective Java that explicitly answers your question?
Example singleton lazy init:
Class main:
public class Main {
public static void main(String[] args) {
System.out.println(Singleton.getInstance("first").value);
System.out.println(Singleton.getInstance("second").value);
System.out.println(Singleton.getInstance("therd").value);
}
}
Class singleton:
public class Singleton {
private static Singleton instance;
public String value;
private Singleton (String s){
this.value =s;
}
public static Singleton getInstance(String param) {
if (instance == null)
instance = new Singleton(param);
return instance;
}
}
When start application, console will contains next strings:
first
first
first
\|/ 73
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'.