I want to know if both singleton and static factory method create only one instance then why there are two concepts for same purpose?
Note: Here term "static factory method" is taken from Effective java book by Joshua bloch where he has written:
"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. This allows immutable classes (Item 15) to use preconstructed instances, or to cache instances as they’re constructed, and dispense them repeatedly to avoid creating unnecessary duplicate objects. The Boolean.valueOf(boolean) method illus- trates this technique: it never creates an object. This technique is similar to the Flyweight pattern [Gamma95, p. 195]. It can greatly improve performance if equivalent objects are requested often, especially if they are expensive to create.
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)"
The point being made by the line "they are not required to create a new object each time they’re invoked" is that (unlike new, which always creates a new object) a factory method could be implemented in some more clever way that reuses an existing object.
Take a look at the of() factory method in Guava's ImmutableList. This method returns "the" empty immutable list -
there's no point constructing a new object every time of() is called, instead the same object is always returned. This is safe because any empty ImmutableList instance is functionally indistinguishable from any other empty instance.
A static factory method is a means of construction, it may return new instances, alternate subclasses of a type, wrap critical logging or registry, compose a number of items into an object, or (maybe) return back a single static instance.
A singleton obtained by any means always resolves back to the same instance. This means there is no variability.
Related
There is a standalone Java application. In it there is a factory method which is called once and creates only one object (if it is possible to create it). I have two questions - which pattern is better for this? And secondly- is it correct to store the object that creates the factory in the factory itself in this case?
The design pattern is Singleton. It's correct to store the object in the factory like the sample. When use singleton, it checks the attribute if it's null. It creates new object if the attribute is null.
The most common pattern for creating a single object in Java is the Singleton Pattern. According to Design Patterns: Elements of Reusable Object-Oriented Software that recorded the pattern, the purpose of the Singleton Pattern is as follows:
Ensure a class only has one instance, and provide a global point of
access to it
There are two ways to create a singleton object: Eagerly and lazily. Eager instantiation is simple because it amounts to the creation of an object and returning it through a getter:
public EagerSingleton {
private static final EagerSingleton INSTANCE = new EagerSingleton();
private EagerSingleton() {}
public static EagerSingleton getInstance() {
return INSTANCE;
}
}
If the creation of the object is expensive (and therefore should be delayed as long as possible) or if there is a reasonable chance that the object may never be needed, it may be a good idea to instantiate the singleton lazily. This is a deceptively difficult task because multiple threads may access the lazily instantiated object and the implementation must ensure that only one object is ever created, regardless of the number of concurrent accessed to the object (i.e. if two threads both see that the singleton has not been created, only one object should be created, not two, and used by both threads).
The safe way to implement a lazy singleton is as follows:
public class Singleton {
private static class SingletonHolder {
public static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
This ensures that the nested static object is not created until getInstance is called. There are a number of optimizations of this scheme, but unless performance is severely needed, the above should be used. Custom implementations of this pattern are difficult to make safe.
Factory seems to be adapted to your requirement.
Note that if you want to master the number of instances of the objects created, a simple way would be to define the class of the instance to create as the factory class itself by defining a private constructor and a static method to create the object is a way.
Note that this way may create a strong coupling between the implementation and its clients. So you could use a less coupled solution such as dependency injection or implementations using an interface.
It's better to use Singleton design pattern when you want to create an object only once and which can be used throughout the application. If you are using factory design pattern for creating only one object and used throughout the application then you may use Singleton pattern for this.
In order to create factory of factory objects then use Abstract Factory design pattern.
I have written 60 Java/J2EE design patterns.
Please refer the link - https://ramesh-java-design-patterns.blogspot.in/
I am reading the book EMF: Eclipse Modeling Framework where its stated:
The EMF programming model strongly encourages, but doesn’t require,
the use of factories for creating objects. Instead of simply using the
new operator to create [an object]...
Why is the use of factories encouraged over new?
Your answer does not have to be EMF specific, as long as it has to do with Java.
You can read Effective Java Item 1: Consider static factory methods instead of constructors. It describes advantages of using factory methods in detail:
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.
A fourth advantage of static factory methods is that they reduce the verbosity of creating parameterized type instances (seems to be outdated since Java 7)
I agree with mostly every answers given here, but those arguments apply generally to every situation in Java, however in this particular case of EMF there is another additional reason: EMF has its own introspection mechanisms, which are used, for instance, for the serialization and deserialization, which doesn't rely in the Java reflection.
For the deserialization, for instance, it reads the XML file, and instantiate the Java objects using the Ecore model information and the respective Factories. Otherwise it would need to use Java reflection.
The answere here is not specific to Java too.
Factory methods have names, it's easier to remember, and less error-prone.
They do not require a new instance to be created each time they are called, you can use preconstructed classes and cache here.
They can return an object of any subtype not only the one called in new
You can parameterize calling "new" object.
The answer to this question is explained in Elegant Objects by Yegor Bugayenko, Chapter 1, Under "1.1 Never use -er names" section.
What the author says is:
A class is a factory of objects.
A class makes objects, though we usually phrase that by saying a class instantiates them:
class Cash {
public Cash(int dollars) {
//...
}
}
Cash five = new Cash(5);
This is different from what we call a Factory Pattern, but only because this "new" operator in Java is not as powerful as it could be. The only thing you can use it for is to make an instance—an object. If we ask class Cash to make a new object, we get a new object. There is no check for whether similar Objects already exist and can be reused, there are no parameters that would modify the behavior of new. etc.
"new" operator is a primitive control for a factory of objects.
Factory Pattern is a more powerful alternative to operator new, but conceptually they are the same. A class is a factory of objects. A class makes objects, keeps track of them, destroys them when necessary, etc.
A Factory Pattern, in Java, works like an extension to the new operator. It makes it more flexible and powerful, by adding an extra logic in front of it.
For example:
class Shapes {
public Shape make(String name) {
if (name.equals("circle")) {
return new Circle();
}
if (name.equals("rectangle")) {
return new Rectangle() ;
}
throw new IllegalArgumentException("not found");
}
}
This is a typical factory in Java that helps us instantiate objects, using textual names of their types. In the end, we still use the new operator. My point is that conceptually, there is not much difference between Factory Pattern and new operator. In a perfect OOP language this functionality would be available in the new operator.
Mainly it is simplicity of creating objects. It's a lot easier to call method from factory than to remember what each parameter in constructor means + it makes changes in code easier
We all know state of an Object is value of it's attributes (instance variables), but if class doesn't has any attribute (no inherited attributes), what would be the state of an Object of such class.
There is a word for such objects - stateless.
There is no such thing as a Java class without a parent class. The default parent would be used, e.g. java.lang.Object.
At a minimum every instance of a class has two attributes: a reference address and a Class type. Note, not every class can be instantiated. There is also some space used in the ClassLoader and any String(s) may (or may not) be interned. This actual implementation might vary slightly on the specific version of the JDK and run-time platform, and additional optimizations can be added by the JIT. However, as a Java developer you are not responsible for this memory management and I would be wary of premature optimization.
first thing
any class we write in java will extend Object class by default if there is no extends written by the developer.
so each and every class will definitely have a parent with no doubt atleast Object class.
second
if you dont put any attributes in your class , obviously it will get all the instance variables except private gets inherited to your class.
so it will have atleast object state but it will not serve any purpose
An object with no data members and links to other objects is a stateless object and in this form can hardly be of any use.
This kind of classes can nevertheless be usefull, because of its methods. It can be...
a base for a further inheritance. It declares/defines some methods, that could be inherited by derived classes. This class will probably be an abstract class, having no objects at all (although not a condition)
a service class. It can define some methods, which in nature do not belong to concrete objects but are used by other objects. Like some all-purpose mathematical operations, a service that returns a current time or similar. These methods can be static, so again no instances are needed.
We call those object stateless. As the name suggests, they have no state.
Referring to other answers/comments, even though every Java object implicitly extends Object, mind that Object has no fields. So even though every object has a runtime address and class attributes, for all practical purposes you can still consider some objects stateless.
Next, it is definitely not true that stateless objects serve no purpose! You can use stateless object for:
1) Grouping functions with similar functionality, similar to java.lang.Math, which groups mathematical functions.
2) Passing functionality as a parameter, e.g. Comparator<T> can be used to sort objects that do not implement Comparable<T>, and it definitely needs no state.
Stateless objects are somehow similar to immutable objects: their state can never be changed and therefore they are always thread-safe.
You may also want to see JEE Stateless Session Beans which differentiate between a converstional state and an instance state.
I am going through Effective Java and some of my things which I consider as standard are not suggested by the book, for instance creation of object, I was under the impression that constructors are the best way of doing it and books says we should make use of static factory methods, I am not able to few some advantages and so disadvantages and so am asking this question, here are the benefits of using it.
Advantages:
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.
A fourth advantage of static factory methods is that they reduce the verbosity
of creating parameterized type instances.
Disadvantages:
The main disadvantage of providing only static factory methods is that
classes without public or protected constructors cannot be subclassed.
A second disadvantage of static factory methods is that they are not
readily distinguishable from other static methods.
Reference: Effective Java, Joshua Bloch, Edition 2, pg: 5-10
I am not able to understand the fourth advantage and the second disadvantage and would appreciate if someone can explain those points. I would also like to understand how to decide to use whether to go for Constructor or Static Factory Method for Object Creation.
Advantage 4: When using a constructor, you have
Foo<Map<Key, Value>> foo = new Foo<Map<Key, Value>>();
vs
Foo<Map<Key, Value>> foo = Foo.createFoo(); // no need to repeat
this advantage will be gone in Java 7, when the diamond syntax will be introduced
Disadvantage 2. You can't easily tell whether a given static method is used for constructor, or for something else.
As for how to choose - there is no single recipe for that. You can weigh all of the above advantages and disadvantages given a use-case, but most often it will just be a decision driven by experience.
If you know the concrete type of the class you are trying to create, then calling the Constructor is fine.
Static Factory Methods are nice when you're not entirely sure how to construct the object you need.
The Factory Method still calls the Constructor on the concrete type, but the method handles the decision on what kind of concrete class to instantiate. The Factory Method then returns an Interface type (rather than a concrete type) so that the concrete type is hidden from the caller.
Disadvantage 2.
A static method that is used for object creation has the same functional layout and appearance as any other static function.
Just by looking at a static method that creates objects you wouldn't know it does this, and the opposite is the relevant part. When you're writing code that you're unfamiliar with, it can be difficult to identify the correct static method that is used to create objects.
The use of the Static Factory Pattern is well documented and can be very useful, especially in Singleton and Multiton situations. Also useful in the initialisation of complex objects.
Please explain the use of the interface Supplier(in Guava) with a suitable example .
The Supplier interface is simply an abstraction of a no-arg function that returns a value... it is a means of getting some instance or instances of an object. Since it is so general, it can be used as many things. Jared explained how the Multimaps factories utilize it as a factory for creating a new instance of a Collection of some type for values.
Given the simplicity of the interface, it also allows for some very powerful decoration of a Supplier's behavior by wrapping it in another Supplier that alters its behavior somehow. Memoization is one example of that. I've used the Suppliers.memoizeWithExpiration method myself as an easy way to make it so some data will only be read from a server at most once in a given period of time.
I'd also recommend taking a look at Guice and how the Provider interface is used in it. Provider is exactly equivalent to Supplier and is central to how Guice works.
Provider allows users to define a custom way of creating new objects of a given class. Users can write a get() method which can execute whatever code is needed to create a new object, so they aren't limited to having Guice use constructors alone to create objects. Here, they are using it to define a custom factory for new instance of an object.
Guice allows injection of a Provider of any dependency. This may return a new instance every time get() is called or it may always return a single instance or anything in between, depending on how the binding the Provider represents is scoped. This also allows for "lazy instantiation" of dependencies... the Provider gives a class a means of creating an object without needing to actually create the object ahead of time. An instance of the object does not need to be created until when, and if, get() is called.
As indicated above, Providers form the basis of scoping in Guice. If you take a look at the Scope interface, you'll notice its single method Provider<T> scope(Key<T> key, Provider<T> unscoped) is defined in terms of Providers. This method takes something that creates a new instance of an object (the Provider<T> unscoped) and returns a Provider<T> based on that which applies whatever policy the scope defines, potentially returning some cached instance of the object rather than creating a new one. The default NO_SCOPE scope simply passes along the unscoped provider, meaning a new instance will be created each time. The SINGLETON scope caches the result of the first call to unscoped.get() and thereafter returns that single instance, ensuring that everything that depends on the singleton-scoped object gets a reference to that single object. Note that the Provider returned by the SINGLETON scope's scope method does essentially the same thing as the Supplier returned by Suppliers.memoize (though it's a bit more complicated).
The main reason we included Supplier in Guava was to support the Multimaps methods that generate arbitrary Multimaps, such as
public static <K,V> Multimap<K,V> newMultimap(Map<K,Collection<V>> map,
Supplier<? extends Collection<V>> factory)
The Supplier creates a Collection that holds all of the values for a given key. The Multimap uses the Supplier whenever you store a key-value pair with a key that's not already in the Multimap.
It's a way to provide an indirect object. You may want to provide another object each time Supplier.get() is called.
For example, i have a singleton class called SmtpMailSender, which takes a hostname for the smtp server. However, the hostname can change at runtime, so instead of taking a String hostname, it takes a Supplier<String> hostname.
Another example use of Supplier:
http://javawayoflife.blogspot.com/2010/06/unit-test-and-new-date.html
Another great use of the class is decoupling - if a component only uses another to obtain a value, do not depend on the concrete implementation, but on this interface.
Anyway, there is some example code here: http://www.slideshare.net/tfnico/google-guava
See the Suppliers class and I guess the methods there will somehow answer your question.