![]() |
VOOZH | about |
Singleton Pattern belongs to Creational type pattern. As the name suggests, the creational design type deals with object creation mechanisms. Basically, to simplify this, creational pattern explains to us the creation of objects in a manner suitable to a given situation. Singleton design pattern is used when we need to ensure that only one object of a particular class is Instantiated. That single instance created is responsible to coordinate actions across the application.
If you look at the illustrated diagram above you will see different objects trying to invoke an object instantiated as a singleton. This single instance of the object is responsible to invoke underneath methods or events.
Guidelines for Singleton Pattern are as follows:
Advantages:
Example
SingletonEagar@2f4d3709 : Singleton Eager initialisation Singleton@1d81eb93 : Singleton Lazy initialisation SingletonSynchronized@34a245ab : Synchronized Singleton
Static nested classes are nested classes that are declared static. In Java, Static classes are a convenient way of grouping classes together. Java doesn't allow you to create top-level static classes; only nested (inner) classes. That is why a static class is also known as a static inner class or static nested class.
Guidelines for Static class are as follows:
Advantages:
Implementation:
Example
20 20 This is Inner Class Constructor... Value of "x" from inside Inner Class is : 20
Now we have understood the concepts and working of both of them and have seen conclusive differences in both of them. Now let's wrap it up by illustrating all differences in a tabular format which is as follows:
| Singleton Pattern | Static Class |
|---|---|
| Singleton is a design pattern. | Static classes are basically a way of grouping classes together in Java. |
| Memory is allocated once the object is created. | Memory is allocated immediately after any of the class members is accessed. |
| Singleton implementation can either have static members or instance members. | Static classes can contain static members only. |
| It can implement any other interface or base class is required. | It cannot implement the interface or any other base class. |
| Singleton classes can be used as a method parameter. | Static class cannot be used as a method parameter. |
| Singleton pattern uses Heap memory. | Static classes use stack memory. |
| It works within the scope of Garbage Collector as it uses Heap memory. | Out of scope for Garbage Collector as it uses stack memory. |
| It supports Dependency Injection (DI) implementation as Singleton follows OOPS concepts. | It cannot implement Dependency Injection (DI) as DI is Interface-driven. |
| Singleton is an architectural pattern and not a language feature. | Static is a language feature and not an Architectural pattern. |
| Disposal of objects is possible. | It cannot dispose of the static class as there is no instance created. |