There are so many types of design patterns to make it easier to solve problems in the program. But this time I only discuss the Singelton, so what is the singleton?
Apa itu Singelton Patttern ?
The Singleton Pattern is a pattern whose goal is that a class can only be instanced once. Unlike regular classes that don't use Singelton, which can create multiple instances.
Why use singleton , why not just use a normal class ?
Example program
public class Singleton
{
private static Singleton instance;
private Singleton(){}
public static Singleton GetInstance()
{
if(instance==null)
instance=new Singleton();
return instance;
}
}
Pros
- You can be sure that a class has only a single instance.
- You gain a global access point to that instance.
- The singleton object is initialized only when itās requested for the first time.
Cons
- Violates the Single Responsibility Principle. The pattern solves two problems at the time.
- The Singleton pattern can mask bad design, for instance, when the components of the program know too much about each other.
- The pattern requires special treatment in a multi-threaded environment so that multiple threads wonāt create a singleton object several times. (using Multi-Thread ā Lazy Load Singleton)
Top comments (0)