Using Singleton Design with Inheritance in a multithreaded Application - java

I am having an application where code is somewhat written like this
public Interface SuperCLass{
//....to do some methods
}
public class BaseClass1 implements SuperCLass{
//....to do some methods
}
public class BaseClass2 implements SuperCLass{
//....to do some methods
}
Now in my application only one object can be instantiated for SuperClass reference, i.e a synchronized singleton.
Now, I can include
public static synchronized SuperCLass getInstance(){
//initialise
}
in any of the base classes, but I cannot include this declaration in SuperClass interface due to which I cannot get back instance of base class using reference of super class.
e.g.
I want to do this(its a very vague example)
BaseClass1 bc1 = BaseClass1.getInstance();
SuperClass sc = bc1.getInstance();
Now somewhere later in the code
bc1=sc.getInstance();
How can this be achieved?
Note: Several threads would be accessing these objects hence synchronisation is mandatory

Instead of using singletons why dont you use dependency injection eg: google guice.
Guice will create the instance of the super class for you and then you can access it via the injector.getInstance() method.

First of all you will have to synchronize the access to the instance. There are plenty of examples on how to do that (such as thread safe publishing of a read only or threadsafe class).
Because a singleton means a static method. You have to decide which implementation is used somewhere. Normally this is through a setInstance method.

One way to make a Superclass method return a Subclass type is through Generics.
You will not be able to make the methods static as you cannot override static methods so this technique will not help you but it would go something like:
public interface SuperClass<T extends SuperClass<T>> {
public T getInstance();
}
public class BaseClass1 implements SuperClass<BaseClass1> {
#Override
public BaseClass1 getInstance() {
// Do my create.
}
}
However, for your specific need of requiring thread-safe Singletons extending a base class you could use an enum as a factory for them and use a Multiton to ensure there is only ever one of them.

Related

why Java 8 interface static methods cannot override Object class methods [duplicate]

I'm confused why the following is not allowed:
public interface MyInterface {
MyInterface getInstance(String name);
}
public class MyImplementation implements MyInterface {
public MyImplementation(String name) {
}
#Override
public static MyInterface getInstance(String name) { // static is not allowed here
return new MyImplementation(name)
}
}
I understand why a method in the interface cannot be static, but why can't the overriding method be?
I want all classes to implement the getInstance(String name) method, but I'm currently limited to only being able to call the method if the object has already been instantiated which kind of defeats the purpose...
*update:* Thanks for the answers, I understand it better now. Basically I shouldn't be trying to make a utility class (or a factory class for that matter) implement an interface (or at least, not in this way)...
Invoking static methods in Java requires you to specify the exact type. It is not possible to invoke static methods polymorphically, eliminating the need for #Override.
Please note that this approach is not universal across all languages: for example, you can override class methods in Objective-C, and Apple's cocoa frameworks make good use of this mechanism to customize their "factory" classes. However, in Java, C++, and C# class methods do not support polymorphic behavior.
Theoretically, Java designers could have let you provide interface method implementations through static methods in case an implementation does not need to access the state from the instance. But the same behavior is simple to achieve with a trivial wrapper:
public class MyImplementation implements MyInterface {
public MyImplementation(String name) {
}
#Override
public MyInterface getInstance() { // static is not allowed here
return getInstanceImpl();
}
public static getInstanceImpl() {
return new MyImplementation(name)
}
}
Java compiler could have done the same thing on your behalf, but seeing a static method implement an instance method is both unusual and confusing, so my guess is that Java designers decided against providing this "piece of magic".
Static methods cannot be subject to polymorphic behavior. That would not make much sense. Image this use case, assuming what you want would be possible:
public void foo(MyInterface i) {
i.getInstance("abc");
}
now I want to call this method with an implementation of MyInterface (class A), but since I cannot pass the class itself, I need to pass an object:
A a = new A();
foo(a);
now inside foo the static override of getInstance is called on the instance of class A. So now I am stuck with creating an object just to call a static method.
My point is that you would still be constrained to create an object in most use cases of polymorphism since in your original interface the method was an instance method.
because implementing an interface makes the implementor the type of the interface. That means instances need to have the methods defined by the type, not the class of the instances.
To put it another way,
public void mymethod
and
public static void mymethod
are NOT the same method declaration. They are completely distinct. If mymethod is defined on an interface, having the second definition simply does not satisfy implementing the interface.
The answer comes down to what it means to implement an interface. When a class implements an interface, that is a promise that every instance of the class will respond to every method in the interface. When you implement the method as static, you make it possible to call the method without an instance of the class - but that doesn't fulfill the inheritance implementation's promise that the method will be callable on every instance of the class.

Alternative of static abstract methods in Java

I'm in a situation where I need all my child classes to implement a common abstract method of a parent class...statically. But apparently Java does not allow abstract static methods...
So, what is an alternative design of such implementation in Java? Below is the code that describes the situation I am in:
Parent class
public abstract class ParentFactory {
/**
* This is a factory class that provides static init method
**/
public abstract static void init();
}
Child class
public class ChildFactory extends ParentFactory {
#Override
public static void init() {
// each child factory has own implementation of init
}
}
EDIT
FYI, I am not asking why this is not valid in Java, I realise the concept of a static method, I know why it is not allowed in Java.
Instead I am asking for help with an alternative design pattern regarding my approach above. Thanks!
If you create a static method, then that method can be accessed with the class itself, i.e. without creating an instance of that class. Therefore, a static method can't be abstract.
I think your problem is in the understanding of the factory pattern. The typical answer to your question would be "use the factory pattern". Because in a factory you could call init on the concrete instance. If you are not using dependency injection and making use of loose coupling through inversion of control, a factory is typically implemented as a singleton. This is to get it from anywhere and there should only be one instance of a factory.
In short, if you want to initialize a factory because you want to subclass the factory (which doesn't make much sense IMHO), you need to create a factory that creates your factory.
If a method is static overriding it makes no sense because inheritance does not apply... that is the reason...
Static code is code related to a class and not to an object or an instance.
you need to modify your code...
You might implement ChildFactory as singleton.
See
https://en.wikipedia.org/wiki/Singleton_pattern

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.

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.

Abstract class with all concrete methods

Are there some practical programming situations for someone to declare a class abstract when all the methods in it are concrete?
Well you could be using a template method pattern where there are multiple override points that all have default implementations but where the combined default implementations by themselves are not legal - any functional implementation must subclass.
(And yes, I dislike the template method pattern ;))
An abstract class is a class that is declared abstract - it may or may not include abstract methods. They cannot be instantiated so if you have an abstract class with concrete methods then it can be subclassed and the subclass can then be instantiated.
Immagine an interface whose declared methods usually show the same default behavior when implemented. When writing a class that needs to support the interface you have to define said default behavior over and over.
To facilitate implementation of your concrete classes you might want to provide an abstract class providing default behavior for each method. To support the interface in a concrete class you can derive from the abstract class and override methods if they deviate from the standard behavior. That way you'll avoid the repeated implementation of the same (redundant) default behavior.
Another possible use case is a decorator which delegates all calls to the wrapped instance. A concrete decorator implementation can override only those methods where functionality is added:
public interface Foo {
public void bar();
}
public abstract class FooDecorator implements Foo {
private final Foo wrapped;
public FooDecorator(Foo wrapped) { this.wrapped = wrapped; }
public void bar() { wrapped.bar(); }
}
public class TracingFoo extends FooDecorator {
//Omitting constructor code...
public void bar() {
log("Entering bar()");
super.bar();
log("Exiting bar()");
}
}
Although I don't really see the necessarity to declare FooDecorator as abstract (non-abstract example: HttpServletRequestWrapper).
Previous answers already hit the main issues, but there's a minor detail that might be worth mentioning.
You could have a factory that returns instances of (hidden) subclasses of the abstract class. The abstract class defines the contract on the resulting object, as well as providing default implementations, but the fact that the class is abstract both keeps it from being instantiated directly and also signals the fact that the identity of the "real" implementation class is not published.
Wondering why no one has pointed to the Practical Example of MouseAdapter:
http://docs.oracle.com/javase/6/docs/api/java/awt/event/MouseAdapter.html
An abstract adapter class for receiving mouse events. The methods in
this class are empty. This class exists as convenience for creating
listener objects.
Nice question :)
One thing is for sure ... this is certainly possible. The template suggestion by krosenvold is one good reason for doing this.
I just want to say that a class must not be declared abstract just for preventing it's instantiation.
This is referred in the Java Language Specification Section 8.1.1.1
When you have an important class but the system cannot create an instance fo this class, because
this class is parent of a lot of classes of the system;
this has a lot of responsability (methods used by a lot of class) for domain's requires;
this class not represents a concrete object;
Servlet Example:
All methods are concrete,
but the base class is useless by itself:
DeleteAuthor.java
Abstract class with concrete doGet method.
doGet calls file pointed to in protected string sql_path.
sql_path is null.
DeleteAuthorKeepBook.java
extends abstract class DeleteAuthor
sets sql_path to delete_author_KEEP_BOOK.sql
DeleteAuthorBurnBook.java
extends abstract class DeleteAuthor
sets sql_path to delete_author_BURN_BOOK.sql

Categories

Resources