java singleton pattern, should all variables be class variables? - java

If a class implements a singleton pattern, should all the variables be declared static?
Is there any reason they shouldn't be declared static? Does it make a difference?

No. The singleton pattern just means that a single instance is the only instance -- it does not mean "make everything statically accessible".
The singleton pattern gives you all the benefits of a "single instance", without sacrificing the ability to test and refactor your code.
Edit:
The point I'm trying to make is that there is a difference between how functionality should be consumed (which depends on context), and how functionality should be initialized.
It may be appropriate that in most cases your object will only ever have a single instance (for example, in your final production system). But there are also other contexts (like testing) that are made much more difficult if you force it to be the only choice.
Also, making something static has more significant implications than just "only one instance of my class should be accessible" -- which is usually the intention.
Further, in software I've worked on, the initialization and lifecycle of objects is often controlled by someone else (I'm talking about DI here) -- and making something static really doesn't help here.

In one common singleton pattern, you do not use statics. You code the class to use ordinary fields, you initialize in the constructor, and then you arrange to execute new MyClass() once, storing the results in some static place.

No, the only thing that is usually static is the reference to the singleton itself (and there are other ways to store that reference, too, such as JNDI or dependency injection containers).
The reason for not declaring fields as static (even though in a singleton pattern you will need only one instance of them) is that this gives you the flexibility to create another, slightly different instance of the normally singleton class. You may want to do that in special situations, such as for testing.
Even if you do not (think you) need that flexibility, there is no reason to give it up. Declaring a field as static has no benefits that you would lose.

You can do this (not necessarily should). But, even for a singleton, I tend to make all the variables object-level rather than class-level because:
I may at some point decide a singleton was a bad idea for that class and having class-level variables will make refactoring harder.
With object-level variables, they only come into existence when you instantiate the singleton. With class-level, they're always there.
Bottom line: I've never been able to think of a disadvantage to having them as object-level so that's how I do it. The above two disadvantages to class-level may be minuscule but they're there. It probably comes down to personal preference in the end.

You can read up on how (one possible way) to create a singleton in Java here:
Wikibooks Design Patterns: Java Singleton
Basically you don't need (nor should) make all things in the class static just because you intend to use something as a singleton. There are several reasons
Check answers from paxdiablo and Thilo
Also don't forget make it all static doesn't make it a singleton you would also need to remove every constructor (and make the default constructor private)

Related

Creating Immutable Objects in Java

I'd like to create a few immutable objects for my codebase. What's the best way to really deliver the message that a given class is intended to be immutable? Should I make all of my fields final, and initialize during object construction? (This seems really awkward...) Should I create some Immutable interface, and have objects implement it? (Since Java doesn't have some standard interface behind this, I thought they had some other way of dealing with it.) What's the standard way this is dealt with? (If it's simply done by adding a bunch of comments around the fields exclaiming that they shouldn't be modified once initialized, that's fine too.)
Should I make all of my fields final, and initialize during object construction?
Yes. And ensure that those types are themselves immutable, or that you create copies when you return values from getter methods. And make the class itself final. (Otherwise your class on its own may be immutable, but that doesn't mean that any instance of your class would be immutable - because it could be an instance of a mutable subclass.)
(This seems really awkward...)
It's hard to know what to suggest without knowing how you find it to be awkward - but the builder pattern can often be useful. I usually use a nested static class for that, often with a static factory method. So you end up with:
Foo foo = Foo.newBuilder()
.setName("asd")
.setPoints(10)
.setOtherThings("whatever")
.build();
Yes and no. Making all fields final is not a guarantee in and of itself. If you'd like to get really in-depth with this there are a number of chapters in Effective Java by Joshua Bloch dealing with immutability and the considerations involved. Item 15 in Effective Java covers the bulk of it and references the other items in question.
He offers these five steps:
Don’t provide any methods that modify the object’s state (known as muta-
tors).
Ensure that the class can’t be extended.
Make all fields final.
Make all fields private.
Ensure exclusive access to any mutable components.
One way to learn how to do all of this is to see how the language designers make classes immutable by reviewing the source for classes like String which are immutable (for example see http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java).
Write a unit test that will fail if your coworkers make the class mutable.
Using Mutability Detector, you can write a test like this:
import static org.mutabilitydetector.unittesting.MutabilityAssert.assertImmutable;
#Test public void isImmutable() {
assertImmutable(MyImmutableThing.class)
}
If a coworker comes along, and, for example, adds a setter method to your class, the test will fail. Your use case is one of the core purposes of Mutability Detector.
Disclaimer: I wrote it.

sharing an object application wide

It's common to have an object used application wide.
What are the different patterns / models / ways to share an object through an application?
Is defining a "main class", then setting a member variable and extending all other classes from this "main class" a good way? Is creating a static class probably the better and cleaner way? What's your prefered pattern?
It's common to have an object used application wide. What are the different patterns / models / ways to share an object through an application?
One common way is to use the singleton pattern. I would avoid that though.
Is defining a "main class", then setting a member variable and extending all other classes from this "main class" a good way
Absolutely not. Aside from anything else, if it's an instance variable then it wouldn't be "shared" with instances of your other classes anyway. It's also a complete abuse of inheritance which would certainly bite you hard in any application of significant size - your other classes wouldn't logically have an inheritance relationship with your "main" class, would they? As a general rule, inheritance should only be used when it's really appropriate - not to achieve a quick fix.
What's your prefered pattern?
Dependency injection. When your application starts up, create all the appropriate objects which need to know about each other, and tell them (usually in the constructor) about their dependencies. Several different objects can all depend on the same object if that's appropriate. You can use one of the many dependency injection frameworks available to achieve this easily.
Dependency injection generally works better than using singletons because:
The class itself doesn't know whether or not the dependency is actually shared; why should it care?
Global state makes unit testing harder
Each class makes its dependencies clearer when they're declared - it's then easier to navigate around the application and see how the classes relate to each other.
Singletons and global factories are more appropriate when they're for things like logging - but even then, it means it's relatively hard to test the logging aspects of a class. It's a lot simpler to create a dependency which does what you need it to, and pass that to the object under test, than it is to add ways of messing around with a singleton (which usually remains "fixed" after initialization).
If you use a framework like Spring which has dependency injection, you can get all the benefits of "global" objects for free without needing to explicitly define them. You just create a reference to them in your application context and you can inject them into any object you'd like without worrying about issues with synchronizing.
Singleton pattern, AFAIK the preferable way in software engineering.
I believe what you are looking for is the Singleton Pattern. With this pattern you are ensured that only one instance of a class can be created in memory.
Example:
public class mySingletonClass {
private static mySingletonClass singleObject;
// Note that the constructor is private to prevent more than one
//instance of the class
private SingletonObjectDemo() {
// Optional Code
}
public static mySingletonClass getSingletonObject() {
if (singleObject == null) {
singleObject = new mySingletonClass();
}
return singleObject;
}
}
That said, you should try to avoid using it; but there are some acceptable cases, one of which is here.

Should I use a pool of objects, a singleton or static methods in a multi-threaded environment?

I have a helper class that creates some objects, like a builder. The helper class does not have a state. It is on a multi-threaded environment; specifically, a web server. Is this class a good candidate for being a singleton?
What would be the difference between implementing this class as a singleton and just using static methods?
What would the effect of thousands of users accessing this object/these methods be?
I could make the class a regular class, but instantiating it every time it is needed would be a waste of memory.
Infact instead of singleton you can make the methods static.
Singleton doesn't have to be only 1, you can create a pool of instances and delegate work depending on the requirement, where as you don't have such control with static methods.
discussion on Singleton vs Static methods is here
As the name suggests, singletons are used to have only one instance of the object present at the time. So singleton does have a state, but you're accessing to that one state wherever you're calling your singleton.
So if you don't need any state saved in your class/method I'd suggest to use static approach.
No need to use singleton here (since you do not need a state), you can use static methods.
Singleton in principle offers more control by allowing a state. There won't be much difference in your case, but static methods will be easier to implement and use.
What would the effect of thousands of users accessing this object/these methods be?
Again, not much difference in both cases, but in Singleton you can have a state, and if you do not implement carefully, your code will be non-thread-safe. Every user calling the static method gets its own "instance" of the method (I think this is what you ask), so no risk of running into thread-safety problems there.
As has been stated before, given that your class doesn't have object state, static methods would work just fine.
However, consider the following - Depending on the overall design of your system, you may want to be able to specify a different implementation of the methods. This is usually done with either subclassing (...), or interface implementation (now the preferred method) - look up the strategy pattern. In either case, being able to provide alternte implementations would require you to not use static methods, but to have an (empty) object to call methods on.

static class vs singleton class

I know this topic has been discussed and killed over and over again, but I still had one doubt which I was hoping someone could help me with or guide me to a pre-existing post on SO.
In traditional C, static variables are stored in data segments and local variables are stored in the stack. Which I would assume will make static variables more expensive to store and maintain when compared to local variables. Right?
When trying to understand in terms of Java or C#, would this be dis-advantage for static classes when compared to singleton class? Since the entire class is loaded into memory before class initialization, I don't see how it can be an advantage unless we have small inline-able functions.
I love Singleton classes, and would hate to see it become an anti-pattern, I am still looking for all the advantages that come with it...and then loose to the argument of thread-safety among others.
-Ivar
Different from C, the static keyword in Java class definition merely means, This is just a normal class like any other class, but it just happens to be declared inside another class to organize the code. In other words, there is no behavioral difference whatsoever between the following 2 way of declaration*:
a)
class SomeOtherClass {
static class Me {
// If you "upgrade" me to a top-level class....
}
}
b)
class Me {
// I won't behave any different....
}
Class definitions are loaded to memory when the class is used for the first time, and this is true for both "static" and "non-static" classes. There are no difference in how memory will be used, either. In older JVMs, objects were always stored in heap. Modern JVMs do allocate objects on stack when that is possible and beneficial, but this optimization is transparent to the coder (it is not possible to influence this behavior via code), and use of the static keyword does not have any effect on this behavior.
Now, back to your original question, as we have seen we really can't compare static classes and Singleton in Java as they are completely different concept in Java (I'm also not sure how static classes would compare with Singleton, but I will focus on Java in this answer). The static keyword in Java is overloaded and has many meanings, so it can be confusing.
Is Singleton automatically an "anti-pattern"? I don't think so. Abuse of Singleton is, but the Singleton pattern itself can have many good uses. It just happens to be abused a lot. If you have legitimate reason to use the Singleton pattern, there is nothing wrong in using it.
*Note: Why write static at all, you might ask. It turns out "non-static" nested classes have their own somewhat complicated memory management implication, and its use is generally discouraged unless you have a good reason (pls refer to other questions for more info).
class SomeOtherClass {
Stuff stuff;
class Me {
void method(){
// I can access the instance variables of the outer instance
// like this:
System.out.println(SomeOtherClass.this.stuff);
// Just avoid using a non-static nested class unless you
// understand what its use is!
}
}
}
Singleton class is essentially a regular top-level class with a private constructor, to guarantee its singleness. Singleton class itself provides a way to grab its instance. Singleton classes are not very easy to test, therefore we tend to stick with the idea of Just Create Once.
static class is essentially a nested class. A nested class is essentially a outer level class which is nested in another class just for packaging convenience. A top-level class can not be declared as static, in Java at least -- you should try it yourself.
would this be dis-advantage for static
classes when compared to singleton
class?
Your this question became somewhat invalid now, according to the above explanation. Furthermore, a static class (of course nested) can also be a singleton.
Further reading:
Inner class in interface vs in class
The differences between one and the other is the memory management, if your app will have to instantiate a lot of things, that will burn the memory like a charm becoming a memory problem, performance and other things...
this could help...
http://butunclebob.com/ArticleS.UncleBob.SingletonVsJustCreateOne
http://www.objectmentor.com/resources/articles/SingletonAndMonostate.pdf
I'm afraid it is an anti-pattern:
http://thetechcandy.wordpress.com/2009/12/02/singletons-is-anti-pattern/

Why use a singleton instead of static methods?

I have never found good answers to these simple questions about helper/utility classes:
Why would I create a singleton (stateless) instead of using static methods?
Why would an object instance be needed if an object has no state?
Often, singletons are used to introduce some kind of global state to an application. (More often than really necessary, to be honest, but that's a topic for another time.)
However, there are a few corner cases where even a stateless singleton can be useful:
You expect to extend it with state in the foreseeable future.
You need an object instance for some particular technical reason. Example: Synchonization objects for the C# lock or the Java synchronized statement.
You need inheritance, i.e., you want to be able to easily replace your singleton with another one using the same interface but a different implementation.Example: The Toolkit.getDefaultToolkit() method in Java will return a singleton whose exact type is system dependent.
You want reference equality for a sentinel value.Example: DBNull.Value in C#.
I could see a case for a stateless singleton being used instead of a static methods class, namely for Dependency Injection.
If you have a helper class of utility functions that you're using directly, it creates a hidden dependency; you have no control over who can use it, or where. Injecting that same helper class via a stateless singleton instance lets you control where and how it's being used, and replace it / mock it / etc. when you need to.
Making it a singleton instance simply ensures that you're not allocating any more objects of the type than necessary (since you only ever need one).
Actually i've found another answer not mentionned here: static methods are harder to test.
It seems most test frameworks work great for mocking instance methods but many of them no not handle in a decent way the mock of static methods.
In most programming languages classes elude a lot of the type system. While a class, with its static methods and variables is an object, it very often cannot implement an interface or extend other classes. For that reason, it cannot be used in a polymorphic manner, since it cannot be the subtype of another type. For example, if you have an interface IFooable, that is required by several method signatures of other classes, the class object StaticFoo cannot be used in place of IFooable, whereas FooSingleton.getInstance() can (assuming, FooSingleton implements IFooable).
Please note, that, as I commented on Heinzi's answer, a singleton is a pattern to control instantiation. It replaces new Class() with Class.getInstance(), which gives the author of Class more control over instances, which he can use to prevent the creation of unneccessary instances. The singleton is just a very special case of the factory pattern and should be treated as such. Common use makes it rather the special case of global registries, which often ends up bad, because global registries should not be used just willy-nilly.
If you plan to provide global helper functions, then static methods will work just fine. The class will not act as class, but rather just as a namespace. I suggest, you preserve high cohesion, or you might end up with weirdest coupling issues.
greetz
back2dos
There is a trade-off between using which one. Singletons may or may not have state and they refer to objects. If they are not keeping state and only used for global access, then static is better as these methods will be faster. But if you want to utilize objects and OOP concepts (Inheritance polymorphism), then singleton is better.
Consider an example: java.lang.Runtime is a singleton class in java. This class allows different implementations for each JVM. The implementation is single per JVM. If this class would have been static, we cannot pass different implementations based on JVM.
I found this link really helpful: http://javarevisited.blogspot.com/2013/03/difference-between-singleton-pattern-vs-static-class-java.html?
Hope it helps!!
Singleton is not stateless, it holds the global state.
Some reasons which I can think of using Singleton are:
To avoid memory leaks
To provide the same state for all modules in an application e.g database connection
For me "Want Object State use Singleton, Want Function use static method"
It depends on what you want. Whenever you want the object state (e.g. Polymorphism like Null state instead of null, or default state), singleton is the appropriate choice for you whereas the static method use when you need function (Receive inputs then return an output).
I recommend for the singleton case, it should be always the same state after it is instantiated. It should neither be clonable, nor receive any value to set into (except static configuration from the file e.g. properties file in java).
P.S. The performance between these 2 are different in milliseconds, so focus on Architecture first.
According to GoF’s book Design Patterns, chapter ‘Singleton’, class operations have the following drawbacks compared to singletons (bold emphasis mine):
More flexible than class operations. Another way to package singleton’s functionality is to use class operations (that is, static member functions in C++ or class methods in Smalltalk). But both of these language techniques make it hard to change a design to allow more than one instance of a class. Moreover, static member functions in C++ are never virtual, so subclasses can’t override them polymorphically.

Categories