Singleton Class or Class with only static fields? [duplicate] - java

This question already has answers here:
Difference between static class and singleton pattern?
(41 answers)
Closed 6 years ago.
what is the better approach?
Let us assume a scenario in which there is a utility class that is used by other classes. What is better to use in this case, a singleton class which can be instantiated exactly once or should i make all the fieds static?

In object-oriented programming generally you should avoid singletons and utility classes if possible.
However, if really needed I'd go with utility class without any fields - just static methods. By definition utilities should be rather set of stateless functions. Such are well testable in comparison to untestable singleton (which is done with static field). If you need to keep the state then go towards true objects.
As stated in the comment, you can have a safe singleton done by dependency injection, without static state.

Related

How to create multiple instances for Singleton class [duplicate]

This question already has answers here:
How to instantiate a Singleton multiple times?
(9 answers)
Closed 9 years ago.
I have created a Singleton class using lazy initialization method. That is the getInstance method is synchronized. But without changing the design pattern is there a way to create multiple instances of the Singleton class. Because changing the Singleton pattern will take lot of architectural changes. Please advice a way to create multiple instances. Please help in Java.
Singleton patten means only one instance is allowed. So there is no question of creating multiple instances.
Though there are some hacks and workarounds like Serializing the Object and De Serializing it back or using different Class loaders but again it violates the basic principle why Singleton pattern is created for.
EDIT: I don't have the required reputation to add it as a comment hence adding it as an answer - as pointed out in the comments, it's a possible duplicate.
A little research and there you have it:
Reference this link
Code
class MySingleton {
private MySingleton() {
}
}
class Test {
public void test() throws Exception {
Constructor<MySingleton> constructor = MySingleton.class.getConstructor();
constructor.setAccessible(true);
MySingleton otherSingleton = constructor.newInstance();
}
}
You want to have multiple instances of a class which can only have one instance by design.
You can, but it is no longer a singleton. Treat it as a normal object which have multiple instances and the restriction is lifted. How you do that depends on your use case.
It will depend on the class behaviour. If the instance is well encapsulated, you can recreate what getInstance method does using reflection, I guess.

Java: when would I ever want to use static methods when I can use a singleton instead? [duplicate]

This question already has answers here:
Difference between static class and singleton pattern?
(41 answers)
Closed 9 years ago.
Having read Difference between static class and singleton pattern?, none of the answers list any advantages for using a static method over a singleton, which leads me to wonder why anyone would ever want to use static methods.
As with all questions of this nature, use the right tool for the job. Use a singleton when your class represents an object that there can be only one of. Use static methods when your methods are appropriate for the class they are members of but do not rely on a specific instance of that class.
In general, use your best judgment. Go for clean, precise, maintainable code, keeping the overall big picture in mind.

Creating static utility methods should not be overused however ? how to avoid it? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
With the time ...lots of utility method are introduced in java project for more complex and simple task.
When using static methods we introduce tight coupling in our code and it make our code more difficult to test, especially if the utility methods are quite complex.
I am just thinking that it now difficult to manage and test these utilities. please guide me in avoiding these utilities methods and how can i organize existing project to remove all STATIC utilities.
Can you help me avoiding static method ?
There is nothing wrong with having lots of static methods.
Static methods are (or should be, read on) stateless, which makes them the easiest methods to test - there's no setup, just call them.
You don't need mocking, because there is no state to deal with.
Regarding being stateless, technically static methods can be stateful if they use static variables to store state. If this is the case, from a good-design perspective they should be converted to instance methods using instance variables to store state, employing the singleton pattern if required.
To contradict the other answers currently available: Static methods are bad!
They do introduce strong coupling. Yes there are cases where it is acceptable. Yes you can make a seam for inside a static method, by making the strategy used inside exchangeable. But as a rule of thumb static are still bad.
To answer the question, how to get rid of static methods. Simple: put them on a proper Object. All statics are gone. Have we improved our code? not much yet. If we replace
callToStaticMethod()
with
new X().callToNoLongerStaticMethod()
we replaced a static call with a constructor call which is essentially just another static method. But now your X is just another dependency, so you can inject it:
class A{
private final X x;
A(X aX){
x = aX;
}
}
Note: there is no need to use Spring or any other framework for this. If you feel like it provide a constructor which uses the default implementation. If you are a purist, introduce an interface for X.
Testing A without relying on the implementation of X becomes trivial and obvious. Same for replacing X in any way.
Static utility methods are not so bad. You can hide a package-private strategy behind the static call. This can be easily tested (and replaced) given that the test case belongs to the same package. Moreover, it makes the code very readable. Of course, the clients of the static utility method can still only use one implementation in their tests. So here is some inflexibility.
Bohemian is right when talking about state. If your static utilities have state you are doing something wrong.
About your question: If you want to avoid static methods you can use the spring framework and define different implementations of utilities that you use and test in different contexts. In this case, however, access to these objects is not so convenient as you must first obtain a reference to the context that knows your utility object.
Nothing wrong with a set of static utility methods that belong together in a class. See for example java.util.Collections. If every method in that class that operates on a List would be specified in the List interface itself, they would have to be implemented by all subclasses. As long as they can be implemented by the public List methods, there is no problem.
Of course, as soon as you start adding methods to the interface (or in case of a class, making methods public) only to be able to put functionality in static methods instead of the class itself, then you're on the wrong path.

Singleton v/s class with static members & methods in Java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between static class and singleton pattern?
Why would one ever require one and only one instance? Same purpose can be achieved using classes with static member variables and static methods.
As far as I can find out, there might be two possible answers to it -
When your class needs to have state and you want only one object of it. From the design point of view, class with static methods & variables are considered to be the Utility classes and shouldn't be keeping any state.
If your class needs to take part in polymorphism and you want only one object of the class(es) which are in the inheritance tree.
It would be really helpful if someone can provide an example from real life scenario or from any Java API where Singleton objects need to participate in Polymorphism / Inheritance?
Collections.emptySet() is a typical example of a singleton that can't be implemented as a static class since, obviously, its goal is to be an instance of the java.util.Set interface. It's not costly to create, but it would be stupid to create a new instance each time an empty set is needed, since the unique instance can be reused.
Classes that perform logging or common access to data bases frequently follow the Singleton pattern. Basically anything that should have instance methods and that is costly to construct.
Scope and behavior are different concerns and should NOT be mixed. You may want your object to be available per use, per thread, per web request, per session or global (Singleton). The reasons for making these adjustments are likely due to resource management and ultimately performance. The behavior inside your class shouldn't have to change if you change its scope.
Singleton is pattern for taking a regular object and controlling its scope with just a little bit of bolt-on code. Ideally though, you really shouldn't really deal with scope at all inside your object and delegate that to a factory or container.
My answer is quite short but it's enough to use exactly common singleton instead of it's static implementation. The answer is:
Popular paradigm (yes it is!)
Threads (synchronization etc.)
Interface implementation (your static class has some restrictions)

Why not singleton instance provided out of box in java? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
You can make class singleton by implementing Singleton pattern. Nowadays singleton class is basic requirement.
Why don't JVM handles Singleton object creation by itself at runtime?
By having marker interface like "Singleton" and creating object instance once by JVM at runtime. Anyways Java compiler adds "extends Object" if Class is not extending any other class. Similar approach can be applied in Singleton case.
This will save lot of time and development effort and discussions around various implementations of Singleton pattern.
1) Synchronized getInstance()
2) Synchronized block inside getInstance() instead of making whole method synchronized
3) Option 2 with singleInstance as volatile member
This will also save lot of time and duplicate efforts if you need to implement singleton pattern in multiple classes(not considering SingletonPatternFactory class which will return singleton instance of any class which is been passed)
Let's take a look at all of the steps needed to create a singleton:
private constructor
a static final field
(optional) if you want the class to be serializable, trivial implementations of readResolve and writeObject
Most singletons that I've come across don't care about serialization, so that third step isn't needed. This leaves you two really, really easy steps.
public class Whatever extends WhateverElse {
public static final Whatever INSTANCE = new Whatever();
private Whatever() {}
}
It's even lazy-loaded, since the constructor won't be run until you access the class, which would only be to get the singleton instance of it. I don't know what your definition of "a lot" is as far as time and development effort, but I don't consider this to be onerous.
Implementing basic design patterns is not the responsibility of the core language, unless there is a compelling reason it should be. Design patterns come and go -- for example, the singleton pattern is widely regarded as an extremely bad pattern that should never be used. Even if you decide to use it anyway, do you want an eager singleton? Lazy singleton? What should happen if instantiation fails for some reason? There's a whole lot of seemingly minor issues to cover, but adding this feature to the language is not a trivial change.
By implementing it yourself you get exactly the features and behavior you want.
You can use an enum instead of a singleton pattern - this is not very complex:
public enum Singleton {
INSTANCE;
}
There are two basic categories of Singletons, those with lazy initialization and those with eager initialization.
Aside from the whole argument on flavors of Singletons, many Java developers consider Singletons to be bad or an anti-pattern. This is probably an area of disagreement among those currently maintaining the Java spec.
Lastly, the same could be said true of most any pattern. There is not a huge need for a language to adopt or endorse any specific set of patterns, IMHO.
You would not want a Singleton interface, since the interface has no behavior of its own. You would want an abstract class... kind of. In reality you would want something a lot more powerful than just an abstract parent. You need to have a private constructor (or a private instantiation method that calls a private constructor and returns the single instance) that has to be called in the getInstance() method defined in the parent (violation of scoping).
What you are suggesting is something that will work outside of the traditional class system. Perhaps it can be done as a new object type (similar to how an enum is not a class), but definitely not as a standard interface or class.

Categories