java singleton class vs final class - java

Can somebody, please explain me clearly on java singleton design pattern class vs java final class.
Can we use a final class instead of using a singleton class?
For a final class we can create the instance of the class and use the methods in that, but not overriding properties, if the methods are static in the final class, then we can just call the methods like ClassName.getMethod, why should we go for singleton instead of final class?

A final class is one which cannot be extended. You can have any number of instances in a final class. The best example of a final class is String. Singleton is a single instance of a class. So both are not exactly same, however you can make your singleton class final to restrict someone from extending it.

You can't extend a final class and there is only single instance for a singleton class. So inheritance concept is not applicable for the final class. But you can create any number of instances in final class but you can't in Singleton.
i.e, final class is immutable class, can create more than one instance but where as Singleton class has only single instance.

A singleton is a class with a single instance for all the life of your program. But a final class, you can have multiple instances of it. The thing is that you cannot inherit from a final class, but nothing stops you to have a lot of instances of it.

A singleton class is usually tied to the ClassLoader. Basically, you should have one per JVM. A final class is something you can't inherit from, but just because it's final it doesn't mean you can't have multiple instances of it (per JVM).
Notice that, when I say per JVM I'm talking about, for instance, a .class file in a .war file deployed once; if the same Web application is deployed multiple times, each one gets its own singleton.

I think your question is more about static versus singleton. Being a final class is not relevant in this context since you cannot override a static method (you can of course define the same signature static method in the extension but this would be irrelevant because the biding will still be "static" in the sense that calling SuperClass.getMethod will always call the definition from SuperClass). This is a classic question and I am sure you can find it answered elsewhere. However, just to give you a short answer, I would say that using a singleton allows you to implement interfaces and pass around your singleton object like any other object.
Maybe I can explain, to whomever gave me -1, what I meant (I thought it was clear enough). The original question is about singleton vs final. But when he explains, he states clearly that he is going to use static methods. He doesn’t realize then that what makes the methods unique in the sense that they belong to a single class is the fact that they are static, and so are class methods instead of instance methods. Being final has no effect: the user can instantiate as many as he wants, it only prevents him from extending the class, which did not seem to me to be the true concern of who asked the question.
On the other hand, he clearly states that he will use static methods on his final class. This seems then to indicate he wants to make it a singleton by using static methods: this is a classic way of doing it, and the question of using static methods versus singleton has been asked before. See for instance Why use a singleton instead of static methods? or Difference between static class and singleton pattern?
When I then write about overriding a static method, I try to explain that static method are not really overridden in the sense that they are not involved in dynamic binding. To give an example, if you have class A with static method foo() and then class B extends class A and redefines static foo(), that’s OK. But calling foo() on an object obj will call the static method belonging to the type of obj, even if you assign it a different object at runtime (this is what I call static binding). In other words, if you declare “A obj = new B()” and call obj.foo() it will still call A.foo()
I don’t know if that explanation helps, I wish whoever gave me -1 explained why.

Related

Java - what's the difference between singleton and static-block-based classes initialization? [duplicate]

What real (i.e. practical) difference exists between a static class and a singleton pattern?
Both can be invoked without instantiation, both provide only one "Instance" and neither of them is thread-safe. Is there any other difference?
What makes you say that either a singleton or a static method isn't thread-safe? Usually both should be implemented to be thread-safe.
The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that's less common, in my experience), so you can pass around the singleton as if it were "just another" implementation.
The true answer is by Jon Skeet, on another forum here.
A singleton allows access to a single
created instance - that instance (or
rather, a reference to that instance)
can be passed as a parameter to other
methods, and treated as a normal
object.
A static class allows only static
methods.
Singleton objects are stored in Heap, but static objects are stored in stack.
We can clone (if the designer did not disallow it) the singleton object, but we can not clone the static class object
.
Singleton classes follow the OOP (object oriented principles), static classes do not.
We can implement an interface with a Singleton class, but a class's static methods (or e.g. a C# static class) cannot.
The Singleton pattern has several advantages over static classes. First, a singleton can extend classes and implement interfaces, while a static class cannot (it can extend classes, but it does not inherit their instance members). A singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded, leading to potential class loader issues. However the most important advantage, though, is that singletons can be handled polymorphically without forcing their users to assume that there is only one instance.
static classes are not for anything that needs state. It is useful for putting a bunch of functions together i.e Math (or Utils in projects). So the class name just gives us a clue where we can find the functions and nothing more.
Singleton is my favorite pattern and I use it to manage something at a single point. It's more flexible than static classes and can maintain it's state. It can implement interfaces, inherit from other classes and allow inheritance.
My rule for choosing between static and singleton:
If there is a bunch of functions that should be kept together, then static is the choice.
Anything else which needs single access to some resources, could be implemented as a singleton.
Static Class:-
You cannot create the instance of static class.
Loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
We cannot pass the static class to method.
We cannot inherit Static class to another Static class in C#.
A class having all static methods.
Better performance (static methods are bonded on compile time)
Singleton:-
You can create one instance of the object and reuse it.
Singleton instance is created for the first time when the user requested.
You can create the object of singleton class and pass it to method.
Singleton class does not say any restriction of Inheritance.
We can dispose the objects of a singleton class but not of static class.
Methods can be overridden.
Can be lazy loaded when need (static classes are always loaded).
We can implement interface(static class can not implement interface).
A static class is one that has only static methods, for which a better word would be "functions". The design style embodied in a static class is purely procedural.
Singleton, on the other hand, is a pattern specific to OO design. It is an instance of an object (with all the possibilities inherent in that, such as polymorphism), with a creation procedure that ensures that there is only ever one instance of that particular role over its entire lifetime.
In singleton pattern you can create the singleton as an instance of a derived type, you can't do that with a static class.
Quick Example:
if( useD3D )
IRenderer::instance = new D3DRenderer
else
IRenderer::instance = new OpenGLRenderer
To expand on Jon Skeet's Answer
The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that's less common IME), so you can pass around the singleton as if it were "just another" implementation.
Singletons are easier to work with when unit testing a class. Wherever you pass singletons as a parameter (constructors, setters or methods) you can instead substitute a mocked or stubbed version of the singleton.
Here's a good article:
http://javarevisited.blogspot.com.au/2013/03/difference-between-singleton-pattern-vs-static-class-java.html
Static classes
a class having all static methods.
better performance (static methods are bonded on compile time)
can't override methods, but can use method hiding. (What is method hiding in Java? Even the JavaDoc explanation is confusing)
public class Animal {
public static void foo() {
System.out.println("Animal");
}
}
public class Cat extends Animal {
public static void foo() { // hides Animal.foo()
System.out.println("Cat");
}
}
Singleton
an object that can only be instantiated once.
methods can be overridden (Why doesn't Java allow overriding of static methods?)
easier to mock then static methods
better at maintaining state
In summary, I would only use static classes for holding util methods, and using Singleton for everything else.
Edits
static classes are lazy loaded as well. Thanks #jmoreno
(When does static class initialization happen?)
method hiding for static classes. Thanks #MaxPeng.
Another advantage of a singleton is that it can easily be serialized, which may be necessary if you need to save its state to disc, or send it somewhere remotely.
I'm not a great OO theorist, but from what I know, I think the only OO feature that static classes lack compared to Singletons is polymorphism.
But if you don't need it, with a static class you can of course have inheritance ( not sure about interface implementation ) and data and function encapsulation.
The comment of Morendil, "The design style embodied in a static class is purely procedural" I may be wrong, but I disagree.
In static methods you can access static members, which would be exactly the same as singleton methods accessing their single instance members.
edit:
I'm actually thinking now that another difference is that a Static class is instantiated at program start* and lives throughout the whole life span of the program, while a singleton is explicitly instantiated at some point and can be destroyed also.
* or it may be instantiated at first use, depending on the language, I think.
To illustrate Jon's point what's shown below cannot be done if Logger was a static class.The class SomeClass expects an instance of ILogger implementation to be passed into its constructor.
Singleton class is important for dependency injection to be possible.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var someClass = new SomeClass(Logger.GetLogger());
}
}
public class SomeClass
{
public SomeClass(ILogger MyLogger)
{
}
}
public class Logger : ILogger
{
private static Logger _logger;
private Logger() { }
public static Logger GetLogger()
{
if (_logger==null)
{
_logger = new Logger();
}
return _logger;
}
public void Log()
{
}
}
public interface ILogger
{
void Log();
}
}
Singleton's are instantiated. It's just that there's only one instance ever created, hence the single in Singleton.
A static class on the other hand can't be instantiated.
Well a singleton is just a normal class that IS instantiated but just once and indirectly from the client code. Static class is not instantiated.
As far as I know static methods (static class must have static methods) are faster than non-static.
Edit:
FxCop Performance rule description:
"Methods which do not access instance data or call instance methods can be marked as static (Shared in VB). After doing so, the compiler will emit non-virtual call sites to these members which will prevent a check at runtime for each call that insures the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue."
I don't actually know if this applies also to static methods in static classes.
Main differences are:
Singleton has an instance/object while static class is a bunch of
static methods
Singleton can be extended e.g. through an interface while static
class can't be.
Singleton can be inherited which supports open/close principles in
SOLID principles on the other hand static class can't be inherited
and we need to make changes in itself.
Singleton object can be passed to methods while static class as it
does not have instance can't be passed as parameters
Distinction from static class
JDK has examples of both singleton and static, on the one hand java.lang.Math is a final class with static methods, on the other hand java.lang.Runtime is a singleton class.
Advantages of singleton
If your need to maintain state than singleton pattern is better choice than static class, because maintaining state in static class leads to bugs, especially in concurrent environment, that could lead to race conditions without adequate synchronization parallel modification by multiple threads.
Singleton class can be lazy loaded if its a heavy object, but static class doesn't have such advantages and always eagerly loaded.
With singleton, you can use inheritance and polymorphism to extend a base class, implement an interface and provide different implementations.
Since static methods in Java cannot be overridden, they lead to inflexibility. On the other hand, you can override methods defined in singleton class by extending it.
Disadvantages of static class
It is easier to write unit test for singleton than static class, because you can pass mock object whenever singleton is expected.
Advantages of static class
Static class provides better performance than singleton, because static methods are bonded on compile time.
There are several realization of singleton pattern each one with advantages and disadvantages.
Eager loading singleton
Double-checked locking singleton
Initialization-on-demand holder idiom
The enum based singleton
Detailed description each of them is too verbose so I just put a link to a good article - All you want to know about Singleton
Singleton is better approach from testing perspective.
Unlike static classes , singleton could implement interfaces and you can use mock instance and inject them.
In the example below I will illustrate this.
Suppose you have a method isGoodPrice() which uses a method getPrice() and you implement getPrice() as a method in a singleton.
singleton that’s provide getPrice functionality:
public class SupportedVersionSingelton {
private static ICalculator instance = null;
private SupportedVersionSingelton(){
}
public static ICalculator getInstance(){
if(instance == null){
instance = new SupportedVersionSingelton();
}
return instance;
}
#Override
public int getPrice() {
// calculate price logic here
return 0;
}
}
Use of getPrice:
public class Advisor {
public boolean isGoodDeal(){
boolean isGoodDeal = false;
ICalculator supportedVersion = SupportedVersionSingelton.getInstance();
int price = supportedVersion.getPrice();
// logic to determine if price is a good deal.
if(price < 5){
isGoodDeal = true;
}
return isGoodDeal;
}
}
In case you would like to test the method isGoodPrice , with mocking the getPrice() method you could do it by:
Make your singleton implement an interface and inject it.
public interface ICalculator {
int getPrice();
}
Final Singleton implementation:
public class SupportedVersionSingelton implements ICalculator {
private static ICalculator instance = null;
private SupportedVersionSingelton(){
}
public static ICalculator getInstance(){
if(instance == null){
instance = new SupportedVersionSingelton();
}
return instance;
}
#Override
public int getPrice() {
return 0;
}
// for testing purpose
public static void setInstance(ICalculator mockObject){
if(instance != null ){
instance = mockObject;
}
test class:
public class TestCalculation {
class SupportedVersionDouble implements ICalculator{
#Override
public int getPrice() {
return 1;
}
}
#Before
public void setUp() throws Exception {
ICalculator supportedVersionDouble = new SupportedVersionDouble();
SupportedVersionSingelton.setInstance(supportedVersionDouble);
}
#Test
public void test() {
Advisor advidor = new Advisor();
boolean isGoodDeal = advidor.isGoodDeal();
Assert.assertEquals(isGoodDeal, true);
}
}
In case we take the alternative of using static method for implementing getPrice() , it was difficult to the mock getPrice().
You could mock static with power mock, yet not all product could use it.
I'm agree with this definition:
The word "single" means single object across the application life
cycle, so the scope is at application level.
The static does not have
any Object pointer, so the scope is at App Domain level.
Moreover both should be implemented to be thread-safe.
You can find interesting other differences about: Singleton Pattern Versus Static Class
One notable difference is differed instantiation that comes with Singletons.
With static classes, it gets created by the CLR and we have not control on it.
with singletons, the object gets instantiated on the first instance it's tried to be accessed.
Below are some main differences between static class and singleton:
1.Singleton is a pattern, not a keyword like static. So for creating a static class static keyword is sufficient while in the case of singleton there is a need to write the logic for the singleton.
2.A singleton class must have a private default instance constructor, while a static class cannot contain any instance constructor.
3.A static class is neither instantiated nor extended, while a singleton class can be.
4.A static class is sealed implicitly, but the singleton class must be decorated as sealed explicitly.
5.It is possible for a singleton to implement the interface or inherit from another class, but the static class neither implements the interface nor extends from any other class.
6.We cannot implement the dependency injection with a static class, but DI is possible with the singleton class because it can be interface driven.
The scope of the static class is at the app domain level because it is managed by the CLR, while the scope of the singleton object is across the application lifecycle.
7.A static class cannot have any destructor but a singleton class can define a destructor.
8.The singleton class instance can be passed as a parameter to another method while a static class cannot be because it contains only static members.
Lazy Loading
Support of interfaces, so that separate implementation can be provided
Ability to return derived type (as a combination of lazyloading and interface implementation)
In many cases, these two have no practical difference, especially if the singleton instance never changes or changes very slowly e.g. holding configurations.
I'd say the biggest difference is a singleton is still a normal Java Bean as oppose to a specialized static-only Java class. And because of this, a singleton is accepted in many more situations; it is in fact the default Spring Framework's instantiation strategy. The consumer may or may not know it's a singleton being passed around, it just treat it like a normal Java bean. If requirement changes and a singleton needs to become a prototype instead, as we often see in Spring, it can be done totally seamlessly without a line of code change to the consumer.
Someone else has mentioned earlier that a static class should be purely procedural e.g. java.lang.Math. In my mind, such a class should never be passed around and they should never hold anything other than static final as attributes. For everything else, use a singleton since it's much more flexible and easier to maintain.
We have our DB framework that makes connections to Back end.To Avoid Dirty reads across Multiple users we have used singleton pattern to ensure we have single instance available at any point of time.
In c# a static class cannot implement an interface. When a single instance class needs to implement an interface for a business contracts or IoC purposes, this is where I use the Singleton pattern without a static class
Singleton provides a way to maintain state in stateless scenarios
Hope that helps you..
In an article I wrote I have described my point of view about why the singleton is much better than a static class:
Static class is not actually canonical class – it’s a namespace with functions and variables
Using static class is not a good practice because of breaking object-oriented programming principles
Static class cannot be passed as a parameter for other
Static class is not suitable for “lazy” initialization
Initialization and using of static class is always hard tracked
Implementing thread management is hard
Singleton class provides an object(only one instance) during the application lifeCycle such as java.lang.Runtime
While Static class only provide static methods such as java.lang.Math
Static methods in Java cannot be overridden, but methods defined in Singleton class can be overridden by extending it.
Singleton Class is capable of Inheritance and Polymorphism to extend a base class, implement an interface and capable of providing different implementations. whereas static not.
For eg: java.lang.Runtime,is a Singleton Class in Java, call to getRuntime() method returns the runtime object associated with the current Java application but ensures only one instance per JVM.
a. Serialization - Static members belong to the class and hence can't be serialized.
b. Though we have made the constructor private, static member variables still will be carried to subclass.
c. We can't do lazy initialization as everything will be loaded upon class loading only.
From a client perspective, static behavior is known to the client but Singleton behavior can be completed hidden from a client. Client may never know that there only one single instance he's playing around with again and again.
I read the following and think it makes sense too:
Taking Care of Business
Remember, one of the most important OO rules is that an object is responsible for itself. This means that issues regarding the life cycle of a class should be handled in the class, not delegated to language constructs like static, and so on.
from the book Objected-Oriented Thought Process 4th Ed.
We can create the object of singleton class and pass it to method.
Singleton class doesn't any restriction of inheritance.
We can't dispose the objects of a static class but can singleton class.

How to call a singleton method from a Java POJO?

I wondered if it would be possible to call from a POJO a singleton bean's method through its interface. Maybe this idea is wrong or the architecture...but this is what I would like to accomplish if it is possible, because this is the architecture of the project.
I notice that when I call getInstance() (the method from the singleton's interface) from the POJO, there is an error occuring, telling me that the method has to be static, but if I make the method static, then I have to write the implementation in the interface and I can't get the singleton instance.
Your current approach with the interface is flawed. By default, all methods in an interface (up until Java 8) are static, and are implemented by instance methods in the implementing class.
This means, this is not an option. After all, you'll need to run the method to create an instance, meaning, you don't have an instance yet, so you have no instance to call it on.
Putting the same static method in an abstract class you extend, is also not a solution: a super class should never be aware of it's subclasses. If it is a static method (which it needs to be), you need to keep it in the class itself: a static method in an abstract class can (through an anonymous implementation of the abstract class) return an instance of the abstract class, but this is not the same as an instance of the subclass, which is what you are looking for.
In order to use this method for the subclass, you will need to inherit it from the super class. But, it will still return an instance of the super class. You'll need to overwrite the method in the subclass by the correct one, so the best solution is to add it straight in your Singleton class.
You are not allowed to have static methods in your interfaces (at least not until Java 8). Something like this is not allowed:
MyInterface var = new MyImplementingClass();
var.staticMethod();
Just remove the interface and do your static method call against the class where the static method resides.
Search a bit for the singleton pattern - the 'standard' way to do this involves classes and not interfaces, so rethink your design.
The idea seems to be wrong. A static method is always at a class level and hence you can never declare a method as static in a Java interface(you can do this in Java 8). However, this seems like the wrong design. If you really want to do something like this -
1)Make the Interface an abstract class.
2)Create a static method called getInstance();
3)Extend the abstract class in your POJO singleton class.
Hope this helps!!

Difference Between singleton class and a class with only static members? [duplicate]

What real (i.e. practical) difference exists between a static class and a singleton pattern?
Both can be invoked without instantiation, both provide only one "Instance" and neither of them is thread-safe. Is there any other difference?
What makes you say that either a singleton or a static method isn't thread-safe? Usually both should be implemented to be thread-safe.
The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that's less common, in my experience), so you can pass around the singleton as if it were "just another" implementation.
The true answer is by Jon Skeet, on another forum here.
A singleton allows access to a single
created instance - that instance (or
rather, a reference to that instance)
can be passed as a parameter to other
methods, and treated as a normal
object.
A static class allows only static
methods.
Singleton objects are stored in Heap, but static objects are stored in stack.
We can clone (if the designer did not disallow it) the singleton object, but we can not clone the static class object
.
Singleton classes follow the OOP (object oriented principles), static classes do not.
We can implement an interface with a Singleton class, but a class's static methods (or e.g. a C# static class) cannot.
The Singleton pattern has several advantages over static classes. First, a singleton can extend classes and implement interfaces, while a static class cannot (it can extend classes, but it does not inherit their instance members). A singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded, leading to potential class loader issues. However the most important advantage, though, is that singletons can be handled polymorphically without forcing their users to assume that there is only one instance.
static classes are not for anything that needs state. It is useful for putting a bunch of functions together i.e Math (or Utils in projects). So the class name just gives us a clue where we can find the functions and nothing more.
Singleton is my favorite pattern and I use it to manage something at a single point. It's more flexible than static classes and can maintain it's state. It can implement interfaces, inherit from other classes and allow inheritance.
My rule for choosing between static and singleton:
If there is a bunch of functions that should be kept together, then static is the choice.
Anything else which needs single access to some resources, could be implemented as a singleton.
Static Class:-
You cannot create the instance of static class.
Loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
We cannot pass the static class to method.
We cannot inherit Static class to another Static class in C#.
A class having all static methods.
Better performance (static methods are bonded on compile time)
Singleton:-
You can create one instance of the object and reuse it.
Singleton instance is created for the first time when the user requested.
You can create the object of singleton class and pass it to method.
Singleton class does not say any restriction of Inheritance.
We can dispose the objects of a singleton class but not of static class.
Methods can be overridden.
Can be lazy loaded when need (static classes are always loaded).
We can implement interface(static class can not implement interface).
A static class is one that has only static methods, for which a better word would be "functions". The design style embodied in a static class is purely procedural.
Singleton, on the other hand, is a pattern specific to OO design. It is an instance of an object (with all the possibilities inherent in that, such as polymorphism), with a creation procedure that ensures that there is only ever one instance of that particular role over its entire lifetime.
In singleton pattern you can create the singleton as an instance of a derived type, you can't do that with a static class.
Quick Example:
if( useD3D )
IRenderer::instance = new D3DRenderer
else
IRenderer::instance = new OpenGLRenderer
To expand on Jon Skeet's Answer
The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that's less common IME), so you can pass around the singleton as if it were "just another" implementation.
Singletons are easier to work with when unit testing a class. Wherever you pass singletons as a parameter (constructors, setters or methods) you can instead substitute a mocked or stubbed version of the singleton.
Here's a good article:
http://javarevisited.blogspot.com.au/2013/03/difference-between-singleton-pattern-vs-static-class-java.html
Static classes
a class having all static methods.
better performance (static methods are bonded on compile time)
can't override methods, but can use method hiding. (What is method hiding in Java? Even the JavaDoc explanation is confusing)
public class Animal {
public static void foo() {
System.out.println("Animal");
}
}
public class Cat extends Animal {
public static void foo() { // hides Animal.foo()
System.out.println("Cat");
}
}
Singleton
an object that can only be instantiated once.
methods can be overridden (Why doesn't Java allow overriding of static methods?)
easier to mock then static methods
better at maintaining state
In summary, I would only use static classes for holding util methods, and using Singleton for everything else.
Edits
static classes are lazy loaded as well. Thanks #jmoreno
(When does static class initialization happen?)
method hiding for static classes. Thanks #MaxPeng.
Another advantage of a singleton is that it can easily be serialized, which may be necessary if you need to save its state to disc, or send it somewhere remotely.
I'm not a great OO theorist, but from what I know, I think the only OO feature that static classes lack compared to Singletons is polymorphism.
But if you don't need it, with a static class you can of course have inheritance ( not sure about interface implementation ) and data and function encapsulation.
The comment of Morendil, "The design style embodied in a static class is purely procedural" I may be wrong, but I disagree.
In static methods you can access static members, which would be exactly the same as singleton methods accessing their single instance members.
edit:
I'm actually thinking now that another difference is that a Static class is instantiated at program start* and lives throughout the whole life span of the program, while a singleton is explicitly instantiated at some point and can be destroyed also.
* or it may be instantiated at first use, depending on the language, I think.
To illustrate Jon's point what's shown below cannot be done if Logger was a static class.The class SomeClass expects an instance of ILogger implementation to be passed into its constructor.
Singleton class is important for dependency injection to be possible.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var someClass = new SomeClass(Logger.GetLogger());
}
}
public class SomeClass
{
public SomeClass(ILogger MyLogger)
{
}
}
public class Logger : ILogger
{
private static Logger _logger;
private Logger() { }
public static Logger GetLogger()
{
if (_logger==null)
{
_logger = new Logger();
}
return _logger;
}
public void Log()
{
}
}
public interface ILogger
{
void Log();
}
}
Singleton's are instantiated. It's just that there's only one instance ever created, hence the single in Singleton.
A static class on the other hand can't be instantiated.
Well a singleton is just a normal class that IS instantiated but just once and indirectly from the client code. Static class is not instantiated.
As far as I know static methods (static class must have static methods) are faster than non-static.
Edit:
FxCop Performance rule description:
"Methods which do not access instance data or call instance methods can be marked as static (Shared in VB). After doing so, the compiler will emit non-virtual call sites to these members which will prevent a check at runtime for each call that insures the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue."
I don't actually know if this applies also to static methods in static classes.
Main differences are:
Singleton has an instance/object while static class is a bunch of
static methods
Singleton can be extended e.g. through an interface while static
class can't be.
Singleton can be inherited which supports open/close principles in
SOLID principles on the other hand static class can't be inherited
and we need to make changes in itself.
Singleton object can be passed to methods while static class as it
does not have instance can't be passed as parameters
Distinction from static class
JDK has examples of both singleton and static, on the one hand java.lang.Math is a final class with static methods, on the other hand java.lang.Runtime is a singleton class.
Advantages of singleton
If your need to maintain state than singleton pattern is better choice than static class, because maintaining state in static class leads to bugs, especially in concurrent environment, that could lead to race conditions without adequate synchronization parallel modification by multiple threads.
Singleton class can be lazy loaded if its a heavy object, but static class doesn't have such advantages and always eagerly loaded.
With singleton, you can use inheritance and polymorphism to extend a base class, implement an interface and provide different implementations.
Since static methods in Java cannot be overridden, they lead to inflexibility. On the other hand, you can override methods defined in singleton class by extending it.
Disadvantages of static class
It is easier to write unit test for singleton than static class, because you can pass mock object whenever singleton is expected.
Advantages of static class
Static class provides better performance than singleton, because static methods are bonded on compile time.
There are several realization of singleton pattern each one with advantages and disadvantages.
Eager loading singleton
Double-checked locking singleton
Initialization-on-demand holder idiom
The enum based singleton
Detailed description each of them is too verbose so I just put a link to a good article - All you want to know about Singleton
Singleton is better approach from testing perspective.
Unlike static classes , singleton could implement interfaces and you can use mock instance and inject them.
In the example below I will illustrate this.
Suppose you have a method isGoodPrice() which uses a method getPrice() and you implement getPrice() as a method in a singleton.
singleton that’s provide getPrice functionality:
public class SupportedVersionSingelton {
private static ICalculator instance = null;
private SupportedVersionSingelton(){
}
public static ICalculator getInstance(){
if(instance == null){
instance = new SupportedVersionSingelton();
}
return instance;
}
#Override
public int getPrice() {
// calculate price logic here
return 0;
}
}
Use of getPrice:
public class Advisor {
public boolean isGoodDeal(){
boolean isGoodDeal = false;
ICalculator supportedVersion = SupportedVersionSingelton.getInstance();
int price = supportedVersion.getPrice();
// logic to determine if price is a good deal.
if(price < 5){
isGoodDeal = true;
}
return isGoodDeal;
}
}
In case you would like to test the method isGoodPrice , with mocking the getPrice() method you could do it by:
Make your singleton implement an interface and inject it.
public interface ICalculator {
int getPrice();
}
Final Singleton implementation:
public class SupportedVersionSingelton implements ICalculator {
private static ICalculator instance = null;
private SupportedVersionSingelton(){
}
public static ICalculator getInstance(){
if(instance == null){
instance = new SupportedVersionSingelton();
}
return instance;
}
#Override
public int getPrice() {
return 0;
}
// for testing purpose
public static void setInstance(ICalculator mockObject){
if(instance != null ){
instance = mockObject;
}
test class:
public class TestCalculation {
class SupportedVersionDouble implements ICalculator{
#Override
public int getPrice() {
return 1;
}
}
#Before
public void setUp() throws Exception {
ICalculator supportedVersionDouble = new SupportedVersionDouble();
SupportedVersionSingelton.setInstance(supportedVersionDouble);
}
#Test
public void test() {
Advisor advidor = new Advisor();
boolean isGoodDeal = advidor.isGoodDeal();
Assert.assertEquals(isGoodDeal, true);
}
}
In case we take the alternative of using static method for implementing getPrice() , it was difficult to the mock getPrice().
You could mock static with power mock, yet not all product could use it.
I'm agree with this definition:
The word "single" means single object across the application life
cycle, so the scope is at application level.
The static does not have
any Object pointer, so the scope is at App Domain level.
Moreover both should be implemented to be thread-safe.
You can find interesting other differences about: Singleton Pattern Versus Static Class
One notable difference is differed instantiation that comes with Singletons.
With static classes, it gets created by the CLR and we have not control on it.
with singletons, the object gets instantiated on the first instance it's tried to be accessed.
Below are some main differences between static class and singleton:
1.Singleton is a pattern, not a keyword like static. So for creating a static class static keyword is sufficient while in the case of singleton there is a need to write the logic for the singleton.
2.A singleton class must have a private default instance constructor, while a static class cannot contain any instance constructor.
3.A static class is neither instantiated nor extended, while a singleton class can be.
4.A static class is sealed implicitly, but the singleton class must be decorated as sealed explicitly.
5.It is possible for a singleton to implement the interface or inherit from another class, but the static class neither implements the interface nor extends from any other class.
6.We cannot implement the dependency injection with a static class, but DI is possible with the singleton class because it can be interface driven.
The scope of the static class is at the app domain level because it is managed by the CLR, while the scope of the singleton object is across the application lifecycle.
7.A static class cannot have any destructor but a singleton class can define a destructor.
8.The singleton class instance can be passed as a parameter to another method while a static class cannot be because it contains only static members.
Lazy Loading
Support of interfaces, so that separate implementation can be provided
Ability to return derived type (as a combination of lazyloading and interface implementation)
In many cases, these two have no practical difference, especially if the singleton instance never changes or changes very slowly e.g. holding configurations.
I'd say the biggest difference is a singleton is still a normal Java Bean as oppose to a specialized static-only Java class. And because of this, a singleton is accepted in many more situations; it is in fact the default Spring Framework's instantiation strategy. The consumer may or may not know it's a singleton being passed around, it just treat it like a normal Java bean. If requirement changes and a singleton needs to become a prototype instead, as we often see in Spring, it can be done totally seamlessly without a line of code change to the consumer.
Someone else has mentioned earlier that a static class should be purely procedural e.g. java.lang.Math. In my mind, such a class should never be passed around and they should never hold anything other than static final as attributes. For everything else, use a singleton since it's much more flexible and easier to maintain.
We have our DB framework that makes connections to Back end.To Avoid Dirty reads across Multiple users we have used singleton pattern to ensure we have single instance available at any point of time.
In c# a static class cannot implement an interface. When a single instance class needs to implement an interface for a business contracts or IoC purposes, this is where I use the Singleton pattern without a static class
Singleton provides a way to maintain state in stateless scenarios
Hope that helps you..
In an article I wrote I have described my point of view about why the singleton is much better than a static class:
Static class is not actually canonical class – it’s a namespace with functions and variables
Using static class is not a good practice because of breaking object-oriented programming principles
Static class cannot be passed as a parameter for other
Static class is not suitable for “lazy” initialization
Initialization and using of static class is always hard tracked
Implementing thread management is hard
Singleton class provides an object(only one instance) during the application lifeCycle such as java.lang.Runtime
While Static class only provide static methods such as java.lang.Math
Static methods in Java cannot be overridden, but methods defined in Singleton class can be overridden by extending it.
Singleton Class is capable of Inheritance and Polymorphism to extend a base class, implement an interface and capable of providing different implementations. whereas static not.
For eg: java.lang.Runtime,is a Singleton Class in Java, call to getRuntime() method returns the runtime object associated with the current Java application but ensures only one instance per JVM.
a. Serialization - Static members belong to the class and hence can't be serialized.
b. Though we have made the constructor private, static member variables still will be carried to subclass.
c. We can't do lazy initialization as everything will be loaded upon class loading only.
From a client perspective, static behavior is known to the client but Singleton behavior can be completed hidden from a client. Client may never know that there only one single instance he's playing around with again and again.
I read the following and think it makes sense too:
Taking Care of Business
Remember, one of the most important OO rules is that an object is responsible for itself. This means that issues regarding the life cycle of a class should be handled in the class, not delegated to language constructs like static, and so on.
from the book Objected-Oriented Thought Process 4th Ed.
We can create the object of singleton class and pass it to method.
Singleton class doesn't any restriction of inheritance.
We can't dispose the objects of a static class but can singleton class.

Why some classes don't need the word "New" when creating its instance?

I am new to Java. One thing confuses me is to why some of the classes need new to instantiate, and why some others do NOT need new to instantiate.
For example, I am looking at log4j, it does not need new.
// get a logger instance named "com.foo"
Logger logger = Logger.getLogger("com.foo");
logger.setLevel(Level.INFO);
Why do some other classes need new? For example, an Employee class:
Employee X = new Employee (John);
X.getwork();
etc etc.
Why we did not say , Logger logger = new Logger(...);? and why were we able to use it even without new, like logger.setLevel(), etc.
The only way to create a new object in Java is with new [1]. However, in some classes, you're not permitted to say new for yourself, you must call a factory method, which might be static (as with your logger example) or not. The author of a class sets this up by making the constructor(s) have access other than public.
Also note that your example may not involve a new object at all. That Logger function might be returning an old object, not a new one.
The following poem by Ogden Nash seems faintly relevant:
This morning I went to the zoo
In order to look at the gnu.
But the old gnu was dead,
and the new gnu, they said,
Was too new a new gnu to view.
[1] Unless you get involved in low-level reflection, or use Object.clone()
In this case, we are dealing with factory methods, as I stated in my comment.
See the relevant API specification on Logger
Retrieve a logger named according to the value of the name parameter. If the named logger already exists, then the existing instance will be returned. Otherwise, a new instance is created.
By default, loggers do not have a set level but inherit it from their neareast ancestor with a set level. This is one of the central features of log4j.
The factory method pattern is a creational design pattern, and, according to Wikipedia, is often useful in the following situations:
The factory pattern can be used when:
The creation of an object precludes its reuse without significant duplication of code.
The creation of an object requires access to information or resources that should not be contained within the composing class.
The lifetime management of the generated objects must be centralized to ensure a consistent behavior within the application.
All three of these are applicable here... who knows what kind of work goes into finding the correct logger? You're not really interested in creating a brand new logger each time you want to use one... instead, your focus is mainly just that -- to use one.
The Creative Commons Wiki also has a relevant article,
Factory methods are sometimes used in place of constructors for any of several reasons:
Some languages (such as Java) do not allow constructors to have useful names
Some languages (such as Java) do not allow constructors to have different names (which may be necessary if you want to use the same method signature for two constructors)
To allow the same instance to be reused instead of recreated each time it is needed (see FlyweightPattern)
I think the third option is probably the most applicable here. Using manual creation of a new Logger, you are unable to adequately share them. Using the getLogger facade enables this to happen transparently.
All in all, the use of factory methods is usually to enable cleaner more straight-forward code without exposing work you don't necessarily care about.
For instance, some classes may prevent you from creating more than one object in the application. It that case you need to call some method for instantiate the class, like the Logger.getLogger(). The getLogger() may have the code like this:
if(uniqueInstance == null) {
uniqueInstance = new Logger();
}
return uniqueInstance;
Where uniqueInstance is an instance of Logger. This is a design pattern called Singleton. In this pattern, you can't instantiate the class because it's constructor is private.
Some other way that you can't instantiate a class is when the class is defined as static.
Classes that have public constructors and aren't static need to be instantiated with the new keyword.
because Logger.getLogger() returns a Logger object. new Logger() calls the constructor which also returns a Logger. This also kind of uses new too, because inside the Logger class is probably something like:
public class Logger {
public static Logger getLogger() {
return new Logger("foo", "bar");
}
}
Well what you are asking is more related to design patterns. The Logger class is following singleton pattern.
Suppose you want that only a single instance of your class gets created accross the application then you can make your constructor private and provide a static method which creates and stores the object of your class when invoked for the first time.
public class SingletonPattern{
private static SingletonPattern instance;
private SingletonPattern(){}
public static synchronized SingletonPattern getInstance(){
if (instance == null){
instance = new SingletonPattern();
}
return instance;
}
}
In this way you can restrict your class to be instantiated only once.
In your example you have to different use cases : the static method that returns an object and the actual constructor call.
The static method is a method that doesn't need to be call on a object, here it's inner mechanism may instantiate an object and return it for futur usage, in this method, there's a call to "new" but the object might be configured, or retrieved from a cache before being return. This is this kind of call
Logger logger = Logger.getLogger("com.foo");
The actual constructor call (which use new) is the normal way to create new object.
You were not technically using the Logger class, but were using a method. You were not technically instantiating the Logger class, nor keeping a reference to it directly as you would with Logger logger = new Logger(). Instead, what you are doing is accessing a method to get back a returned instance. It would be nice to see the class definition. However, more than likely what you have is a static method inside of the class. And the class is more than likely defined with a private constructor. This allows the methods to be accessed without instantiating the class. You can see a good explanation of this, and of static in java here: https://stackoverflow.com/a/1844388/1026459
Some classes cannot be instantiated outside of themselves (e.g. the Math class, these classes have non-public constructors). Of those classes, some provide methods that return instances of the class (e.g. the InetAddress class). These are called factory methods. They are static methods that return instances of the class they're in, so the new keyword need not be used (it is instead used inside of the factory methods). For example:
public class A {
private A() {}
public A createAnA() { return new A(); }
}
Here, createAnA() is the factory method.

Java member object inside class of same type

I am looking at a codebase and I often see something like:
public class SomeClass
{
protected static SomeClass myObject;
//...
public static SomeClass getObject()
{
return myOjbect
}
}
I'd like to make sure I understand the purpose behind this. Is it to ensure one instance of the class gets shared even if it is instantiated multiple times? I am not sure about the vocabulary here, or else I'd search for the answer, so if this pattern has a name, please let me know.
Also, this seems a little chicken-and-egg definition because the class includes an object of the type of the class. Why isn't this actually paradoxical?
Thanks!
This is really only common with the Singleton Pattern where there is only this one instance of the class. While it has its uses, Singleton is over- and misused more often than not (usually to disguise procedural programming as OO). It also occurs very often in example code for Java AWT or Swing, where you typically subclass Frame / JFrame, and create an instance in a main method inside the same class.
Also, this seems a little
chicken-and-egg definition because the
class includes an object of the type
of the class. Why isn't this actually
paradoxical?
Why do you think it is? The class mainly describes what members instances of this type have - but a static member does not belong to an instance, it belongs to the class itself, so it doesn't have anything to do with the "blueprint" role of the class. Static members are really somewhat un-OO because of that.
But even on the instance level you can have references of the same type. For example, an entry in a linked list would typically have two references to the next and previous entries, which are of the same class.
This is called the Singleton design pattern.
You are correct in stating that the purpose is to ensure only one instance of the class gets created.
Wikipedia has a preyty good article on the pattern.
The pattern you mentioned is called "Singleton", but from your code sample it is not clear if this is really what is intended. Due to the fact that the member is protected, I would guess not - if there are subclasses, then there would probably not be a single instance.
It's called Singleton. You ensure the creation of just ONE (1) object of a given class.
You should add a private Constructor, so the only one who create the object is the class.
public class SomeClass
{
// Using private constructor
protected static SomeClass myObject = new SomeClass();
private SomeClass(){
//...
}
public static SomeClass getObject()
{
return myOjbect
}
}
Much much more here, in Wikipedia
You may want to take a look to Factory Pattern
It's not all that uncommon; it can be a good way to implement the Singleton pattern. There can be other uses as well - sometimes you will want a handful - and no more - of objects of a given class; that class is a good place to hang onto them. In the event that you don't want other classes to be able to create objects of this class, it is common to give the class a private constructor as well.
It's not paradoxical, because the compiler can be aware of a reference to the class before it has fully compiled the class. Later - if you like to think of it this way - it can "fill in the blanks".

Categories

Resources