Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design pattern: Factory that creates one object

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?

like image 252
Vitalii T Avatar asked Mar 07 '23 10:03

Vitalii T


2 Answers

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.

like image 154
Bejond Avatar answered Mar 15 '23 21:03

Bejond


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.

like image 42
Justin Albano Avatar answered Mar 15 '23 21:03

Justin Albano