Design pattern: Factory that creates one object - java

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/

Related

What are the essential elements of the Singleton pattern?

The core question is in the title but the answer I believe is right is as follows;
It ensures that only one instance is created
It provides a global point of access to an object
I am asking because I am unsure that the above is correct answer to the question. I did a little research but the above answer keep coming up. Is there anything to add or is the answer wrong completely.
Yes you are correct.
Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine. The singleton class must provide a global access point to get the instance of the class. Singleton pattern is used for logging, drivers objects, caching and thread pool.
Singleton pattern is not difficult to understand.
Singleton it use to limit the numbers of object instance to one. Generally it use with factories.
Singleton class is like this :
public class YourClass{
private static final YourClass INSTANCE = new YourClass();
private YourClass{Your code..}
//This is the factorie
public static YourClass getInstance(){return INSTANCE;}
}
You can't create many instance of your class. The program return always the same object.
You can find many other explanation on this page : https://www.tutorialspoint.com/java/java_using_singleton.htm

Creating class static getter instead of object link

When you have many classes, it is often necessary to get access to fields/methods of one class from the other one. I'm not very experienced with Java and I've recently found this method which seem to be very convenient (better than passing variables from one class to another):
class MyClass {
private static MyClass _instance = null;
public MyClass(){
...
}
public static getInstance(){
if (_instance == null) {
_instance = new MyClass();
}
return _instance;
}
}
Now in any other class I can simply do
MyClass.getInstance().callSomething()
However I do not see such way of accessing other classes in Java examples and tutorials that I find in the Internet. So that got me thinking, are there maybe some potential problems with such approach? Especially when you have many classes and hence many such static calls in each?
MyClass.getInstance().callSomething()
However I do not see such way of accessing other classes in Java
examples and tutorials that I find in the Internet.
The approach you have specified is one of the most commonly used design pattern called Singleton pattern.
In Java the Singleton pattern will ensure that there is only one instance of a class is created in the Java Virtual Machine. It is used to provide global point of access to the object. In terms of practical use Singleton patterns are used in logging, caches, thread pools, configuration settings, device driver objects. Design pattern is often used in conjunction with Factory design pattern.
However, your code does not seem to fulfill the contract of Singleton Design pattern. It primarily requires your class to have only private constructors (to avoid other classes from instantiating it).
public MyClass(){ // Constructor needs to be private
...
}
Also the getInstance() method does not even seem to be valid.
Try this:
public static MyClass getInstance(){
It is recommended to implement Singleton in Java 5 or above version using Enum.
Enum is thread safe and implementation of Singleton through Enum ensures that your singleton will have only one instance even in a multithreaded environment
Follow this link for detailed understanding of Singleton pattern using Enum
Here is a good link which can help you understand Singleton pattern in detail.
This design pattern is called Singleton, have a look at the following question.
What is so bad about singletons?

Creating a factory that returns singletons

I have common code (multiple class that I call controllers) that needs to be shared by multiple packages in the project.
I was thinking of creating a factory, that returns these controllers.
So, the factory would have a hashmap, that can return the controller asked for or create a new one if not created.
The controllers have common code and since I don't need to create multiple instances of these controller, I think they should be singletons.
Does this seem like a good approach?
I think what you need is a Multiton pattern.
The multiton pattern is a design pattern similar to the singleton,
which allows only one
instance of a class to be created. The multiton pattern expands on the
singleton concept to manage a map of named instances as key-value
pairs. Rather than have a single instance per application (e.g. the
java.lang.Runtime object in the Java programming language) the
multiton pattern instead ensures a single instance per key.
public class FooMultiton {
private static final Map<Object, FooMultiton> instances = new HashMap<Object, FooMultiton>();
private FooMultiton() {
// no explicit implementation
}
public static synchronized FooMultiton getInstance(Object key) {
// Our "per key" singleton
FooMultiton instance = instances.get(key);
if (instance == null) {
// Lazily create instance
instance = new FooMultiton();
// Add it to map
instances.put(key, instance);
}
return instance;
}
// other fields and methods ...
}
The controllers have common code and since I don't need to create
multiple instances of these controller, I think they should be
singletons.
You need single instance does not necessarily mean that you need a Singleton Pattern. You can have a single instance and pass that on subsequent calls to that. Don't necessarily enforce singletonness using private constructor.
Also read Evil Singletons for more on down points of Singletons. After reading that if you still feel you need Singleton then go with it.
Yes it does. The Singleton design pattern suffer for several problems, one of which is that Singletons cannot be extended.
However, if you retrieve these controllers via a ControllerFactory.createControllerX() instead of ControllerX.getInstace(), you will be able to extended ControllerX in future and all its client will not be aware of using an extended version. Which is a really good thing

why are there java singleton classes? When would you need to use one

I understand that a singleton class is one where there can be only one instantiation, but I don't understand why this would be useful. Why won't you just create a class with static variables and methods and use synchronize if needed to make sure that no two threads were executing a method in the class simultaneously. I just don't get why anyone would go through the trouble of creating this kind of class. I know I'm missing something here.
Thanks,
While I agree with the other answers, the OP was asking why not have a class with all static methods (possibly with static fields) instead of a singleton where you have one instance.
Why use Singletons?
You can Google "singleton" to find all sorts of reasons. From JavaWorld:
Sometimes it's appropriate to have
exactly one instance of a class:
window managers, print spoolers, and
filesystems are prototypical examples.
Typically, those types of
objects—known as singletons—are
accessed by disparate objects
throughout a software system, and
therefore require a global point of
access. Of course, just when you're
certain you will never need more than
one instance, it's a good bet you'll
change your mind.
Why use a Singleton instead of a class with all static methods?
A few reasons
You could use inheritance
You can use interfaces
It makes it easier to do unit testing of the singleton class itself
It makes it possible to do unit testing of code that depends on the singleton
For #3, if your Singleton was a database connection pool, you want to insure that your application has only one instance, but do unit testing of the database connection pool itself without hitting the database (possibly by using a package-scope constructor or static creational method):
public class DatabaseConnectionPool {
private static class SingletonHolder {
public static DatabaseConnectionPool instance = new DatabaseConnectionPool(
new MySqlStatementSupplier());
}
private final Supplier<Statement> statementSupplier;
private DatabaseConnectionPool(Supplier<Statement> statementSupplier) {
this.statementSupplier = statementSupplier;
}
/* Visibile for testing */
static DatabaseConnectionPool createInstanceForTest(Supplier<Statement> s) {
return new DatabaseConnectionPool(s);
}
public static DatabaseConnectionPool getInstance() {
return SingletonHolder.instance;
}
// more code here
}
(notice the use of the Initialization On Demand Holder pattern)
You can then do testing of the DatabaseConnectionPool by using the package-scope createInstanceForTest method.
Note, however, that having a static getInstance() method can cause "static cling", where code that depends on your singleton cannot be unit tested. Static singletons are often not considered a good practice because of this (see this blog post)
Instead, you could use a dependency injection framework like Spring or Guice to insure that your class has only one instance in production, while still allowing code that uses the class to be testable. Since the methods in the Singleton aren't static, you could use a mocking framework like JMock to mock your singleton in tests.
A class with only static methods (and a private contructor) is a variant where there is no instance at all (0 instances).
A singleton is a class for which there is exactly 1 instance.
Those are different things and have different use cases. The most important thing is state. A singleton typically guards access to something of which there is logically only ever one. For instance, -the- screen in an application might be represented by a singleton. When the singleton is created, resources and connections to this one thing are initialized.
This is a big difference with a utility class with static methods - there is no state involved there. If there was, you would have to check (in a synchronized block) if the state was already created and then initialize it on demand (lazily). For some problems this is indeed a solution, but you pay for it in terms of overhead for each method call.
Database instances is one place singletons are useful, since a thread only wants one DB connection. I bet there are a lot of other instances like database connections where you only want one instance of something and this is where you would use a singleton.
For me the reason to prefer singleton over a class with static methods is testability. Let's say that I actually need to ensure that there really is one and only one instance of a class. I could do that with either a singleton or a static class with only static methods. Let's also say that I'd like to use this class in another class, but for testing purposes I'd like to mock the first class out. The only way to do that is to inject an instance of the class into the second class and that requires that you have a non-static class. You still have some pain with respect to testing -- you might need to build in some code you can invoke with reflection to delete the singleton for test purposes. You can also use interfaces (though that would explicitly would allow the use of something other than the singleton by another developer) and simply provide the singleton as an instance of the interface to the class that uses it.
One consideration is that making a singleton an instance allows you to implement an interface. Just because you want to control instantiation to it, does not mean you want every piece of code to know that it's a singleton.
For example, imagine you had a connection provider singleton that creates DB connections.
public class DBConnectionProvider implements ConnectionProvider {}
If it were a class with static methods, you couldn't inject the dependency, like this:
public void doSomeDatabaseAction(ConnectionProvider cp) {
cp.createConnection().execute("DROP blah;");
}
It would have to be
public void doSomeDatabaseAction() {
DBConnectionProvider.createConnection().execute("DROP blah;");
}
Dependency injection is useful if you later want to unit test your method (you could pass in a mocked connection provider instead) among other things.
Use the singleton pattern to encapsulate a resource that should only ever be created (initialised) once per application. You usually do this for resources that manage access to a shared entity, such as a database. A singleton can control how many concurrent threads can access that shared resource. i.e. because there is a single database connection pool it can control how many database connections are handed out to those threads that want them. A Logger is another example, whereby the logger ensures that access to the shared resource (an external file) can be managed appropriately. Oftentimes singletons are also used to load resources that are expensive (slow) to create.
You typically create a singleton like so, synchronising on getInstance:
public class Singleton {
private static Singleton instance;
private Singleton(){
// create resource here
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
But it is equally valid to create it like so,
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton(){
// create resource here
}
public static Singleton getInstance() {
return instance;
}
}
Both methods will create a single instance PER classloader.
A singleton has the advantatage over a class with static variables and methods : it's an object instance, which can inherit from a class (example : an application that ahas a single principal JFrame), and extend one or more interfaces (and thus be treated as any other object implementing these interfaces).
Some people think that singletons are useless and dangerous. I don't completely agree, but some points about it are valid, and singletons should be used carefully.
Static classes used in place of singletons are even worse in my opinion. Static classes should be mainly used to group related functions which don't share a common resource. java.util.Collections is a good example. It's just a bunch of functions that aren't tied to any object.
Singletons, on the other hand, are true objects. Ideally, singleton should be implemented without singleton pattern in mind. This will allow you to easily switch to using multiple instances if you suddenly need it. For example, you may have only one database connection, but then you have to work with another, completely unrelated database at the same time. You just turn your singleton into a "doubleton" or "tripleton" or whatever. If you need, you can also make its constructor public which will allow creation of as many instances as you want. All this stuff isn't so easy to implement with static classes.
Simply put, a singleton is a regular class that has one instance globally available, to save you from all the trouble of passing it everywhere as a parameter.
And there is not much trouble in creating a singleton. You just create a regular class with a private constructor, then implement one factory method, and you're done.
When would you need to use one?
There are many objects we only need one of: thread pools, caches, dialog boxes, objects that handle preferences and registry settings, objects used for logging, and objects that act as device drivers to devices like printers and graphic cards. For many of these types of object if we were to intantiate more than one we would run intol all sorts of problems like incorrect program behavior or overuse of resources
Regarding the usage of synchronization it is definitly expensive and the only time syncrhonization is relevant is for the first time or the unique instatiation once instantiated we have no further need to synchronize again. After the first time through, syncrhonization is totally unneeded overhead :(
Others have provided better answers while I was replying, but I'll leave my answer for posterity. It would appear unit testing is the big motivator here.
For all intents and purposes, there is no reason to prefer a singleton to the approach you described. Someone decided that static variables are capital-b Bad (like other sometimes useful features like gotos) because they're not far off from global data and in response we have the workaround of singletons.
They are also used with other patterns. See Can an observable class be constructed as a singleton?

What is the difference between a Singleton pattern and a static class in Java? [duplicate]

This question already has answers here:
Difference between static class and singleton pattern?
(41 answers)
Closed 5 years ago.
How is a singleton different from a class filled with only static fields?
Almost every time I write a static class, I end up wishing I had implemented it as a non-static class. Consider:
A non-static class can be extended. Polymorphism can save a lot of repetition.
A non-static class can implement an interface, which can come in handy when you want to separate implementation from API.
Because of these two points, non-static classes make it possible to write more reliable unit tests for items that depend on them, among other things.
A singleton pattern is only a half-step away from static classes, however. You sort of get these benefits, but if you are accessing them directly within other classes via `ClassName.Instance', you're creating an obstacle to accessing these benefits. Like ph0enix pointed out, you're much better off using a dependency injection pattern. That way, a DI framework can be told that a particular class is (or is not) a singleton. You get all the benefits of mocking, unit testing, polymorphism, and a lot more flexibility.
Let's me sum up :)
The essential difference is: The existence form of a singleton is an object, static is not. This conduced the following things:
Singleton can be extended. Static not.
Singleton creation may not be threadsafe if it isn't implemented properly. Static not.
Singleton can be passed around as an object. Static not.
Singleton can be garbage collected. Static not.
Singleton is better than static class!
More here but I haven't realized yet :)
Last but not least, whenever you are going to implement a singleton, please consider to redesign your idea for not using this God object (believe me, you will tend to put all the "interesting" stuffs to this class) and use a normal class named "Context" or something like that instead.
A singleton can be initialized lazily, for one.
I think, significant thing is 'object' in object oriented programing. Except from few cases we should restrict to usage of static classes. That cases are:
When the create an object is meaningless. Like methods of java.lang.Math. We can use the class like an object. Because the behavior of Math class methods doesn't depend on the state of the objects to be created in this class.
Codes to be used jointly by more than one object method, the codes that do not reach the object's variables and are likely to be closed out can be static methods
Another important thing is singleton is extensible. Singleton can be extended. In the Math class, using final methods, the creation and extension of the object of this class has been avoided. The same is true for the java.lang.System class. However, the Runtime class is a single object, not a static method. In this case you can override the inheritance methods of the Runtime class for different purposes.
You can delay the creation of a Singleton object until it is needed (lazy loading). However, for static method classes, there is no such thing as a condition. If you reach any static member of the class, the class will be loaded into memory.
As a result, the most basic benefit to the static method class is that you do not have to create an object, but when used improperly, it will remove your code from being object-oriented.
The difference is language independent. Singleton is by definition: "Ensure a class has only one instance and provide a global point of access to it. " a class filled with only static fields is not same as singleton but perhaps in your usage scenario they provide the same functionality. But as JRL said lazy initiation is one difference.
At least you can more easily replace it by a mock or a stub for unit testing. But I am not a big fan of singletons for exactly the reason you are describing : it are global variables in disguise.
A singleton class will have an instance which generally is one and only one per classloader. So it can have regular methods(non static) ones and they can be invoked on that particular instance.
While a Class with only static methods, there is really no need in creating an instance(for this reason most of the people/frameworks make these kind of Util classes abstract). You will just invoke the methods on class directly.
The first thing that comes to mind is that if you want to use a class with only static methods and attributes instead of a singleton you will have to use the static initializer to properly initialise certain attributes. Example:
class NoSingleton {
static {
//initialize foo with something complex that can't be done otherwise
}
static private foo;
}
This will then execute at class load time which is probably not what you want. You have more control over this whole shebang if you implement it as a singleton. However I think using singletons is not a good idea in any case.
A singleton is a class with just one instance, enforced. That class may have state (yes I know static variables hold state), not all of the member variables or methods need be static.
A variation would be a small pool of these objects, which would be impossible if all of the methods were static.
NOTE: The examples are in C#, as that is what I am more familiar with, but the concept should apply to Java just the same.
Ignoring the debate on when it is appropriate to use Singleton objects, one primary difference that I am aware of is that a Singleton object has an instance that you can pass around.
If you use a static class, you hard-wire yourself to a particular implementation, and there's no way to alter its behavior at run-time.
Poor design using static class:
public class MyClass
{
public void SomeMethod(string filename)
{
if (File.Exists(filename))
// do something
}
}
Alternatively, you could have your constructor take in an instance of a particular interface instead. In production, you could use a Singleton implementation of that interface, but in unit tests, you can simply mock the interface and alter its behavior to satisfy your needs (making it thrown some obscure exception, for example).
public class MyClass
{
private IFileSystem m_fileSystem;
public MyClass(IFileSystem fileSystem)
{
m_fileSystem = fileSystem;
}
public void SomeMethod(string filename)
{
if (m_fileSystem.FileExists(filename))
// do something
}
}
This is not to say that static classes are ALWAYS bad, just not a great candidate for things like file systems, database connections, and other lower layer dependencies.
One of the main advantages of singletons is that you can implement interfaces and inherit from other classes. Sometimes you have a group of singletons that all provide similar functionality that you want to implement a common interface but are responsible for a different resource.
Singleton Class :
Singleton Class is class of which only single instance can exists per classloader.
Helper Class (Class with only static fields/methods) :
No instance of this class exists. Only fields and methods can be directly accessed as constants or helper methods.
These few lines from this blog describes it nicely:
Firstly the Singleton pattern is very
useful if you want to create one
instance of a class. For my helper
class we don't really want to
instantiate any copy's of the class.
The reason why you shouldn't use a
Singleton class is because for this
helper class we don't use any
variables. The singleton class would
be useful if it contained a set of
variables that we wanted only one set
of and the methods used those
variables but in our helper class we
don't use any variables apart from the
ones passed in (which we make final).
For this reason I don't believe we
want a singleton Instance because we
do not want any variables and we don't
want anyone instantianting this class.
So if you don't want anyone
instantiating the class, which is
normally if you have some kind of
helper/utils class then I use the what
I call the static class, a class with
a private constructor and only
consists of Static methods without any
any variables.

Categories

Resources