In Java we can do the following to initialize class and call method inside that class:
public class MyClass {
public String myClassMethod() {
return "MyClass";
}
}
.
public class Test {
public static void main(String[] args) {
MyClass myClass = new MyClass(); // initialize MyClass
myClass.myClassMethod();// call a method
}
}
If my class is an enum class, implementation will be the following:
public enum MyEnumClass {
INSTANCE;
public String myEnumClassMethod() {
return "MyEnumClass";
}
}
.
public class Test {
public static void main(String[] args) {
MyEnumClass myEnumClass = MyEnumClass.INSTANCE;
myEnumClass.myEnumClassMethod();
}
}
Both of these cases works in the same way, but it is said to be better in the enum implementation. My question is why and how it is happening?
An enum is essentially a singleton pattern.
The JVM handles the initialization and storage of enum instances. To see this most clearly you can write:
public enum MyEnumClass {
INSTANCE("some value for the string.");
private final String someString;
private MyEnumClass(final String someString) {
this.someString = someString;
}
public String getSomeString(){
return someString;
}
}
And in another class:
public static void main(String[] args) {
final MyEnumClass myEnumClass = MyEnumClass.INSTANCE;
system.out.println(myEnumClass.getSomeString());
}
This would print out "some value for the string.".
This demonstrates that the enum instances are initialised at class load time, i.e. as if by the static initialiser.
Or put another way:
new MyClass() == new MyClass();
Is always false, whereas:
MyEnumClass.INSTANCE == MyEnumClass.INSTANCE;
Is always true. i.e. MyEnumClass.INSTANCE is always the same MyEnumClass.INSTANCE whereas a new MyClass is created every time your call new MyClass().
This brings us nicely to your question of "better".
An enum is a singleton instance with various nifty methods for converting String enum names into a reference to the singleton instance that it represents. It also guarantees that if you de-serialize an enum there won't be two separate instances like there would for a normal class.
So an enum is certainly much better as a robust and threadsafe singleton than a class.
But we cannot have two instances of INSTANCE with the different values for someString so the enum is useless as a class...
In short enums are good for what they're good for and classes are good for what they're good for. They are not substitutes and therefore cannot be compared in any meaningful way expect when one is used as the other.
It's a simple implementation of the Singleton pattern, relying on the mechanisms of how Enum's work.
If you use MyEnumClass.INSTANCE a second time, you'll get the same object instance.
In contrast, new MyClass(); will create a new object.
See also discussion here:
What is the best approach for using an Enum as a singleton in Java?
There would possibly be more to learn by reading Java Language Spec Section 8-9
Related
This answer says that we can't instantiate more than one object at a time via private constructors. I have modified the code which does just the opposite:
class RunDatabase{
public static void main(String[] args){
Database db = Database.getInstance("hello");//Only one object can be instantiated at a time
System.out.println(db.getName());
Database db1 = Database.getInstance("helloDKVBAKHVBIVHAEFIHB");
System.out.println(db1.getName());
}
}
class Database {
//private static Database singleObject;
private int record;
private String name;
private Database(String n) {
name = n;
record = 0;
}
public static synchronized Database getInstance(String n) {
/*if (singleObject == null) {
Database singleObject = new Database(n);
}
return singleObject;*/
return new Database(n);
}
public void doSomething() {
System.out.println("Hello StackOverflow.");
}
public String getName() {
return name;
}
}
And as expected both the strings are being printed. Did I miss something?
We can't instantiate more than one object at a time via private constructors.
No, we can. A private constructor only avoids instance creation outside the class. Therefore, you are responsible for deciding in which cases a new object should be created.
And as expected both the strings are being printed. Did I miss something?
You are creating a new instance every time the getInstance method is called. But your commented code contains a standard lazy initialization implementation of the singleton pattern. Uncomment these parts to see the difference.
Other singleton implementations you can look over here.
Private constructors are used to stop other classes from creating an object of the "Class" which contains the private constructor.
This is done to provide the singleton pattern where only a single instance of the class is used.
The code that you have mentioned is supposed to create just one instance of the class and use that instance only to perform all the operations of that class. But you have modified the code which violates the singleton design pattern.
Why do we need a private constructor at all?
Basically 3 reasons:
if you don't want the user of the class creates an object directly, and instead use builders or similars,
if you have a class defined for constants only, then you need to seal the class so the JVM don't create instances of the class for you at runtime.
singletons
I have an object say A that loads some data from disk and it takes a bit long time to load. Many of other objects need its methods and data so I don't want neither any time I need it create a new one nor passing it through class constructor. Is there any way to create an instance of the class A only once at the beginning of the running project and all the other objects have access to the object A?
I apologize if my question is duplicated but I don't have any idea about what keywords relate to this question to find related questions.
In that case you are dealing with the Singleton Design Pattern you should declare youre class like this:
public class SingleObject {
//create an object of SingleObject
private static SingleObject instance = new SingleObject();
//make the constructor private so that this class cannot be
//instantiated
private SingleObject(){}
//Get the only object available
public static SingleObject getInstance(){
return instance;
}
public void showMessage(){
System.out.println("Hello World!");
}
}
And then you can use it as intended.
In fact the approach here is to use static members like this:
public class Vehicle {
private static String vehicleType;
public static String getVehicleType(){
return vehicleType;
}
}
The static modifier allows us to access the variable vehicleType and the method getVehicleType() using the class name itself, as follows:
Vehicle.vehicleType
Vehicle.getVehicleType()
Take a look at Java static class Example for further information.
Sure. The design pattern is called a singleton. It could look like this:
public class Singleton {
private static Singleton instance;
private Singleton () {}
/*
* Returns the single object instance to every
* caller. This is how you can access the singleton
* object in your whole application
*/
public static Singleton getInstance () {
if (Singleton.instance == null) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
}
All objects can use the singleton by calling Singleton.getInstance()
I am developing a design pattern, and I want to make sure that here is just one instance of a class in Java Virtual Machine, to funnel all requests for some resource through a single point, but I don't know if it is possible.
I can only think of a way to count instances of a class and destroy all instance after first is created.
Is this a right approach? If not, is there any other way?
Use the singleton pattern. The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance().
The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance() method (which must be public) then simply returns this instance,
public class Singleton {
private static Singleton instance;
/**
* A private Constructor prevents any other class from
* instantiating.
*/
private Singleton() {
// nothing to do this time
}
/**
* The Static initializer constructs the instance at class
* loading time; this is to simulate a more involved
* construction process (it it were really simple, you'd just
* use an initializer)
*/
static {
instance = new Singleton();
}
/** Static 'instance' method */
public static Singleton getInstance() {
return instance;
}
// other methods protected by singleton-ness would be here...
/** A simple demo method */
public String demoMethod() {
return "demo";
}
}
Note that the method of using “lazy evaluation” in the getInstance() method (which
is advocated in Design Patterns), is not necessary in Java because Java already uses “lazy
loading.” Your singleton class will probably not get loaded unless its getInstance()
is called, so there is no point in trying to defer the singleton construction until it’s needed
by having getInstance() test the singleton variable for null and creating the singleton
there.
Using this class is equally simple: simply get and retain the reference, and invoke methods on it:
public class SingletonDemo {
public static void main(String[] args) {
Singleton tmp = Singleton.getInstance();
tmp.demoMethod();
}
}
Some commentators believe that a singleton should also provide a public final
clone() method that just throws an exception, to avoid subclasses that “cheat” and
clone() the singleton. However, it is clear that a class with only a private constructor
cannot be subclassed, so this paranoia does not appear to be necessary.
That's the well known Singleton pattern: you can implement this as follows:
public class SingletonClass {
//this field contains the single instance every initialized.
private static final instance = new SingletonClass();
//constructor *must* be private, otherwise other classes can make an instance as well
private SingletonClass () {
//initialize
}
//this is the method to obtain the single instance
public static SingletonClass getInstance () {
return instance;
}
}
You then call for the instance (like you would constructing a non-singleton) with:
SingletonClass.getInstance();
But in literature, a Singleton is in general considered to be a bad design idea. Of course this always somewhat depends on the situation, but most programmers advice against it. Only saying it, don't shoot on the messenger...
There is a school of thought that considers the Singleton pattern to in fact be an anti-pattern.
Considering a class A that you only wish to have one of, then an alternative is to have a builder or factory class that itself limits the creation of the number of objects of Class A, and that could be by a simple counter.
The advantage is that Class A no longer needs to worry about that, it concentrates on its real purpose. Every class that uses it no longer has to worry about it being a singleton either (no more getInstance() calls).
You want the Singleton pattern. There is an excellent discussion of how to implement this properly. If you do this right, there will only ever be one instance of the class.
Essentially what you are going to do is create a class, hold a single instantiated object of that class at the static level, and provide a static accessor to get it (getInstance() or similar). Make the constructor final so people can't create their own instances out of the blue. That link above has plenty of great advice on how to do this.
Use enum. In Java enum is the only true way to create a singleton. Private constructors can be still called through reflection.
See this StackOverflow question for more details:
Implementing Singleton with an Enum (in Java)
Discussion:
http://javarevisited.blogspot.com/2012/07/why-enum-singleton-are-better-in-java.html
I can only think of a way to count instances of a class and destroy all instance after first is created. Is this a right approach ? If not, is there any other way ?
The correct technical approach is to declare all of the constructors for the class as private so that instances of the class can only be created by the class itself. Then you code the class only ever create one instance.
Other Answers show some of the ways to implement this, according to the "Singleton" design pattern. However, implementing a singleton like this has some drawbacks, including making it significantly harder to write unit tests.
I prefer lazy singleton class, which overrides readResolve method.
For Serializable and Externalizable classes, the readResolve method allows a class to replace/resolve the object read from the stream before it is returned to the caller. By implementing the readResolve method, a class can directly control the types and instances of its own instances being deserialized.
Lazy singleton using /Initialization-on-demand_holder_idiom:
public final class LazySingleton {
private LazySingleton() {}
public static LazySingleton getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final LazySingleton INSTANCE = new LazySingleton();
}
private Object readResolve() {
return LazyHolder.INSTANCE;
}
}
Key notes:
final keyword prohibits extension of this class by sub-classing
private constructor prohibits direct object creation with new operator in caller classes
readResolve prohibits creation of multiple instances of class during object de-serialization
For that you need to use singleton pattern, I am just posting a demo code for that that may useful for your understanding.
E.g: If I want only one object for this Connect class:
public final class Connect {
private Connect() {}
private volatile static Connect connect = null;
public static Connect getinstance() {
if(connect == null) {
synchronized (Connect.class) {
connect = new Connect();
}
}
return connect;
}
}
Here the constructor is private, so no one can use new keyword to make a new instance.
class A{
private A(){
}
public static A creator(A obj){
A ob=new A();
return ob;
}
void test(){
System.out.println("The method is called");
}
}
class Demo{
public static void main(String[] args){
A ob=null;
ob=A.creator(ob);
ob.test();
}
}
What is the purpose of getInstance() in Java?
During my research I keep reading that getInstance() helps achieve a Singleton design pattern (which means just one instance across the whole program to my understanding). But can't I just use static? Isn't that the whole point of static?
If I were to just have static methods and fields, how would it differ from using getInstance()? Is there a "scope" of static? For example, one instance per method or class?
And if they are different, in what cases would I choose getInstance() over using static?
I apologize if the question is unclear, I am sure I am missing something on the subject matter, I just can't figure out what.
Thank you for any and all advice.
Static will not give you a singleton. Since there is no way of making a top-level class a singleton in Java, you have getInstance methods which will implement some logic to to be sure there is only one instance of a class.
public class Singleton {
private static Singleton singleton;
private Singleton(){ }
public static synchronized Singleton getInstance( ) {
if (singleton == null)
singleton=new Singleton();
return singleton;
}
}
Check out this top answer: Static Classes In Java
The above code will allow only one instance to be created, and it's clean, however as of Java 1.6, it is better to create singleton's as such since it is slightly more elegant IMHO:
public enum MyEnumSingleton {
INSTANCE;
// other useful methods here
}
Source: http://www.vogella.com/tutorials/DesignPatternSingleton/article.html
Singleton
A singleton allows you to use a single reference to a java Object. For example, here is a singleton which contains a number;
public class MySingleton {
private int myNumber;
private static MySingleton instance;
public static MySingleton getInstance() {
if (instance == null) {
instance = new MySingleton();
}
return instance;
}
private MySingleton() {}
public void setMyNumber(int myNumber) {
this.myNumber = myNumber;
}
public int getMyNumber() {
return myNumber;
}
}
Now we are going to set the value of this number in the A class:
public class A {
/*...*/
MySingleton mySingleton = MySingleton.getInstance();
mySingleton.setMyNumber(42);
/*...*/
}
Then, you can access this value from another class:
public class B {
/*...*/
MySingleton mySingleton = MySingleton.getInstance();
int number = mySingleton.getMyNumber();
/*...*/
}
In this class the number variable will have the value 42. This is the advantage of a singleton over a simple object:
All the values stored in the singleton will be accessible from
"everywhere".
Static class
The purpose is different, here the advantage is to use an object without having to create it.
For example:
public static class MyStaticClass {
public static void sayHello() {
System.out.println("Hello");
}
}
Now you can use the sayHello() method from any classes by calling:
MyStaticClass.sayHello();
The exact method of implementing a singleton, for example using a factory method called getInstance(), isn't that relevant to the question, which is "static methods vs singleton with instance methods".
Classes are themselves effectively singletons, so from that aspect they are similar.
The main difference is that static methods are not part of class hierarchy - they are not inherited, which means the static method option locks you forever to using that exact class and it can't be referred to in any other way, such being an implementation of some interface or a super class.
Instances however don't have this problem, so you can code for example:
class MySingleton implements SomeInterface {
...
}
SomeInterface instance = MySingleton.getInstance();
I prefer to use static too, but sometimes getInstance() is helpful to have some functions that will be related to the object, in which you can modify variables. if you are simply making some util functions that do not need an instance of an object, use static.
When you are using someone's libraries, you never know if a function body needs a class instance. That's why a lot of library classes are using getInstance().
Instead of checking for null, I like this a little better.
public class SingleObject {
//create an object of SingleObject
private static SingleObject instance = new SingleObject();
//make the constructor private so that this class cannot be
//instantiated
private SingleObject(){}
//Get the only object available
public static SingleObject getInstance(){
return instance;
}
}
Called with...
public class SingletonPatternDemo {
public static void main(String[] args) {
//illegal construct
//Compile Time Error: The constructor SingleObject() is not visible
//SingleObject object = new SingleObject();
//Get the only object available
SingleObject object = SingleObject.getInstance();
}
}
Full code from: http://www.tutorialspoint.com/design_pattern/singleton_pattern.htm
One overlooked reason to use a singleton instead of static class member variables is that the static member variables MAY use space and garbage collector time even in the event the class is never instantiated. Consider how many classes are available to you in rt.jar and what a small fraction of them you probably use in any given application. Also consider that using getInstance ensures your "constructor" has run before any of the member variables are accessed. I almost universally see getInstance as synchronized but I feel this is a bad idea. If anyone ever adds a synchronized blocking method calls to Singleton.getInstance().unsynchronized() could be needlessly held up.
private static Singleton instance = null;
private Singleton() {}
public final static Singleton getInstance() {
return (instance != null) ? instance : makeInstance();
}
private final static synchronized Singleton makeInstance() {
return ( instance != null ) ? instance : ( instance = new Singleton() );
}
Let's say i have a class, and I made only one instance of it and i don't need more than that.
Should i just make the class static ? (not the class itself but the functions and the variables).
In the example below should i make the class static if i won't make more than one instance of it ?
public class Foo {
int num1;
int num2;
public void func() {
// Something in here
}
}
public static void main(String[] args) {
Foo bar = new Foo(); //I don't need more than one instance of that class.
}
If your class has no state, say:
class NoState {
static int sum(int i1, int i2) { return i1 + i2; }
}
then it makes sense to use static methods.
If you must ensure that there is only one instance of your class, then you could use a singleton, but be careful: global state can be evil.
Not as bad as a singleton, you could use static fields/methods: it can be useful is some situations but should not be abused.
In any other situations (= most of the time), just use normal instance variables/methods.
You can use an enum to define a singleton.
public enum Foo {
INSTANCE;
int num1;
int num2;
public void func() {
// Something in here
}
}
public static void main(String[] args) {
Foo bar = Foo.INSTANCE;
}
However, this is only need if you want to enforce one instance. Otherwise, I would just use new Foo(); and call it only once, if you only need one.
You can use Singleton. However, make sure if Singleton is what is really required - sometimes singletons gets overused where simple class with static methods might suffice. There are many ways to create singleton as explained What is an efficient way to implement a singleton pattern in Java?
Note that with Java 5, enum is the preferred way to create singleton.
You say that i don't need more than that so my answer is that not make more than one and if you really like to enforce the instance that it should be only one for class then use the enum best way to implement the singleton in java
for example in datasource one really needs singleton
public enum UserActivity {
INSTANCE;
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
private UserActivity() {
this.dataSource = MysqlDb.getInstance().getDataSource();
this.jdbcTemplate = new JdbcTemplate(this.dataSource);
}
public void dostuff() {
...
}
}
and if you really need that then use it otherwise go with your current logic
A class that must be instantiated once and only once, is called a singleton. That knowledge should help you narrow down your search for information. To give you a head start:
Difference between static class and singleton pattern?
Why use a singleton instead of static methods?
Basically static methods and fields means that you don't need any instances of the class.
In you case you need 'singleton' class, you can either use enum or make it a singleton by yourself, using the specific set of rules.
It really depends on the scope of your application. If you want this object to be used as a singleton you would provide a static method to get the one and only instance of the class.
public class Foo
{
private static Foo instance ....
private Foo()
{
.....
}
public static Foo getInstance()
{
return instance;
}
}
If you plan to use a framework like spring you would just add one object to the application context.
<bean class="....Foo" id="fooInstance" scope="singleton">
....
</bean>
But maybe, you can refractor this class to hold only static methods. Then you can mark the class as final and provide a private constructor.
public final class Utils
{
private Utils(){}
public static .... doFoo(....)
{
....
}
}