I read a lot on stackoverflow regarding the creation of singleton classes using enum.
I must have missed something because i can't reach the INSTANCE anywhere.
this is my code:
public class UserActivity {
private DataSource _dataSource;
private JdbcTemplate _jdbcTemplate;
static enum Singleton {
INSTANCE;
private static final UserActivity singleton = new UserActivity();
public UserActivity getSingleton() {
return singleton;
}
}
public UserActivity() {
this._dataSource = MysqlDb.getInstance().getDataSource();
this._jdbcTemplate = new JdbcTemplate(this._dataSource);
}
public void dostuff() {
...
}
}
and outside I'm trying to do
UserActivity.INSTANCE.getSingleton()
or
UserActivity.Singleton.
but eclipse's code completion doesn't find anything
thanks!
The trick is to make the enum itself the singleton. Try this:
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() {
...
}
}
// use it as ...
UserActivity.INSTANCE.doStuff();
INSTANCE is a member of Singleton, not of UserActivity - so you'd need:
UserActivity.Singleton.INSTANCE.getSingleton();
However, you haven't actually made UserActivity a singleton - normally you'd make the type itself an enum, not embed an enum within the type...
public class UserActivity {
private DataSource _dataSource;
private JdbcTemplate _jdbcTemplate;
private static enum Singleton { // private, why not
INSTANCE;
private static final UserActivity singleton = new UserActivity();
public UserActivity getSingleton() {
return singleton;
}
}
private UserActivity() { // private !!(*)
this._dataSource = MysqlDb.getInstance().getDataSource();
this._jdbcTemplate = new JdbcTemplate(this._dataSource);
}
public static UserActivity getInstance() {
return UserActivity.Singleton.INSTANCE.getSingleton();
}
public void dostuff() {
...
}
}
and call UserActivity.getInstance().doStuff();
You can't call the constructor (*) and you can only get an instance of your UserActivity() class via the INSTANCE in the private enum - which is guaranteed to be created once and only once
Related
Hi Can please someone tell me the correct way how I can instantiate the below given singleton class?
public class BillPughSingleton {
private BillPughSingleton(){}
private static class SingletonHelper{
private static final BillPughSingleton INSTANCE = new BillPughSingleton();
}
public static BillPughSingleton getInstance(){
return SingletonHelper.INSTANCE;
}
}
Try with:
BillPughSingleton bill = BillPughSingleton.getInstance();
you can rewrite your class simply like this and no more need to SingletonHelper class
public class BillPughSingleton {
private static BillPughSingleton INSTANCE;
private BillPughSingleton(){}
public static BillPughSingleton getInstance(){
if (INSTANCE==null) {
INSTANCE = new BillPughSingleton();
}
return INSTANCE;
}
}
for instansiate you can try this:
BillPughSingleton instance = BillPughSingleton.getInstance();
you can find more another example here
Example class with singleton design pattern.
class Singleton {
private static Singleton instance;
private int x;
private Singleton() {
x = 5;
}
public static synchronized Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
public void doSomething() {
System.out.println("Hello");
}
}
I'm just wondering can I create this class with same variables and methods declared as static. Is it same as the singleton?
Singleton should be considered only if all three of the following criteria are satisfied:
Ownership of the single instance cannot be reasonably assigned
Lazy initialization is desirable
Global access is not otherwise provided for
Yes, It is the same.
If you really need to implement a singelton pattern I would recommend using an enum:
public enum MySingelton{
INSTANCE;
private final String[] variable = new String[]{"test", "test2};
public void randomFunction(){
}
}
Call it with:
MySingelton.INSTANCE.randomFunction();
With an enum implementation it's guaranteed that only one instance is created and that it's available all the time. Also it's possible to serialize and deserialize the singelton without creating multiple copies of it.
More information can be found here:
What is an efficient way to implement a singleton pattern in Java?
http://www.drdobbs.com/jvm/creating-and-destroying-java-objects-par/208403883?pgno=3
Since the purpose of the singleton pattern is to ensure that a single instance of a class exists, yes, you could use static members to achieve the same effect.
So instead of
public class Singleton {
private static Singleton theInstance = new Singleton();
private int aVar = 10;
public void aMethod() {
System.out.println(aVar);
}
public static Singleton getInstance() {
return theInstance;
}
}
you could do
public class FakeSingleton {
private static int aVar = 10;
public static void aMethod() {
System.out.println(aVar);
}
}
and have exactly the same functionality (instead of Singleton.getInstance().aMethod() you would write FakeSingleton.aMethod()).
Using the singleton pattern can be advantageous if you want lazy initialization, so that the singleton is only initialized when it is first needed, as follows:
public class Singleton {
private static Singleton theInstance = null;
private int aVar = 10;
public void aMethod() {
System.out.println(aVar);
}
public static Singleton getInstance() {
if (theInstance == null) {
theInstance = new Singleton();
}
return theInstance;
}
}
(Note that the above is not thread-safe, in multithreaded code you will need to add synchronization.)
I am new to java singleton, I want to make my class singleton, so that I have one instance of it in my code.
The class which I want to be singleton is extend another class which its constructor have two entry.
Below code is, what I have done! but it is not correct!
how can I write my singleton
public class Singleton extends Parent{
private Ui ui;
private Store store;
private singleton(Ui ui, Store store) {
super(ui, store);
// TODO Auto-generated constructor stub
}
private static class singletonHolder() {
// My problem is here: how to set value for super class?!
public static final singleton INSTANCE = new singleton();
}
public static singleton getInstance() {
return singletonHolder.INSTANCE;
}
protected Object readResolve() {
return getInstance();
}
public void SetStore(Store dstore){
store = dstore;
}
public void SetUi(Ui uid){
ui = uid;
}
}
Lets assume we've got base class:
public class Base {
public Base(int i) {
/* ... */
}
/* ... */
}
We want to create singleton based on this class. The problem is that class have public constructor, so extending it will result in singleton having public constructor, too:
public class SingletonBase extends Base {
private static final SingletonBase _instance = new SingletonBase();
private SingletonBase() {
super(0);
}
public SingletonBase(int i) { // Want to avoid this!
super(i)
}
public static void getInstance() {
return _instance;
}
/* ... */
}
Singleton, of course, cannot have public constructors, so we want to avoid this.
So, what is most elegant way/pattern to have proper Singleton with functionalities from class Base?
Edit: Modifying Base class is prohibited, since it is from an external library.
Constructors are not inherited. So just
delete this part and you'll get what you need.
public SingletonBase(int i) { // Want to avoid this!
super(i)
}
Additionally, you may want to make the Base class
abstract so that no one can instantiate it by mistake
by calling the Base constructor directly.
public abstract class Base {
public Base(int i) {
/* ... */
}
/* ... */
}
public class SingletonBase extends Base {
private static final SingletonBase _instance = new SingletonBase();
private SingletonBase() {
super(0);
}
public static SingletonBase getInstance() {
return _instance;
}
/* ... */
}
You could make SingletonBase just a normal subclass and delegate the Singleton-part to a different class.
I don't know what your specific context is, but you would have Subclass extends Base and somewhere else you would have your SingletonContainer or something like that where you have the method public static Subclass getInstance().
That way, you would have your usual inheritance and also the Singleton effect, since the SingletonContainer would be responsible for keeping only a single instance of Subclass.
It is not because you inherit from a class that have a public constructor that you have to create the same public constructor, you can do :
public class SingletonBase extends Base {
private static final SingletonBase _instance = new SingletonBase();
private SingletonBase() {
super(0);
}
public static void getInstance() {
return _instance;
}
/* ... */
}
Or even :
public class SingletonBase extends Base {
private static final SingletonBase _instance = new SingletonBase();
private SingletonBase() {
super(0);
}
private SingletonBase(int i) { // Want to avoid this!
super(i)
}
public static void getInstance() {
return _instance;
}
/* ... */
}
Can anyone please tell me whether this is a singleton class or not?
public class Final_output{
Cafe_factory obj=null;
private Final_output()
{
obj = new Cafe_factory();
obj.getOrder("French Fries");
obj.getOrder("Biryani");
obj.getOrder("Ice-cream");
}
public static void main(String args[])
{
new Final_output();
}
}
Cafe_factory is another class in the same package.
This is not a Singleton.
Singleton for Example is:
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
Not, it's not. Because you can't create instances of this class outside of it (at least one instance should exist). For the other hand - you can create as many instances inside main as you wish (so it's not singleton either).
Here is an example of Singleton:
public class MySingleton{
private MySingleton(){}
private static InstanceHolder{
private static final MySingleton instance = new MySingleton();
}
public static MySingleton getInstance(){
return InstanceHolder.instance;
}
}
Its not.
A singleton has as objective to limit to 1 the number of instances of the same class that can be created, and provide static methods to retrieve this instance.
This is typically done via a private constructor and static methods to retrieve this unique instance. Here neither Final_output nor Cafe_factory respect this contract so none of them use the singleton pattern.
Since you could create n amount of new Cafe_Factory objects in your code also outside the Final_output class, no it is not a singleton. A singleton is never created with the new keyword. Instead, you fetch an instance of it via a static method.
this :
public class Final_output{
private static Cafe_factory obj = null;
private Final_output()
{
obj = getCafeInstance();
}
public static getCafeInstance(){
if(null == obj){
obj = new Cafe_factory();
obj.getOrder("French Fries");
obj.getOrder("Biryani");
obj.getOrder("Ice-cream");
}else{
return obj;
}
}
}
NO This is not a singleTon
public class Final_output{
private static Final_output ourInstance = new Final_output();
Cafe_factory obj=null;
private Final_output() {
obj = new Cafe_factory();
obj.getOrder("French Fries");
obj.getOrder("Biryani");
obj.getOrder("Ice-cream");
}
public Final_output getINstance(){
return ourInstance;
}
}