How can I instantiate singleton class implemented in Bill Pugh method? - java

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

Related

lazy loaded Singleton - will a static field call cause instantiation

i have the following what you might call a lazy loaded singleton per the definition:
public class MySingleton {
public static String myTrigger="a trigger";
private MySingleton(){
}
private static enum LazyLoad {
IMDB_LOOKUP_INSTANCE;
private static final IMDB_LOOKUP = new MySingleton();
}
public static MySingleton getInstance() {
return LazyLoad.IMDB_LOOKUP_INSTANCE.IMDB_LOOKUP;
}
}
What happens when i make a call like this:
String someString = MySingleton.myTrigger;
will the singleton not get instantiated ?
There are issues with your enum. So, i have modified it and the following code works and initializes MySingleton.
public class MySingleton {
public static String myTrigger="a trigger";
private MySingleton(){
System.out.println("Initialized");
}
private static enum LazyLoad {
IMDB_LOOKUP_INSTANCE(new MySingleton());
MySingleton value;
LazyLoad(MySingleton value){
this.value = value;
}
private MySingleton getValue(){
return this.value;
}
}
public static MySingleton getInstance() {
return LazyLoad.IMDB_LOOKUP_INSTANCE.getValue();
}
}
Class gets loaded when you call MySingleton.myTrigger. But if you want your MySingleton to get initialized on class loading, put MySingleton.getInstance() in static block.
After testing (By putting a print statement in the constructor) , I found that -
In the above code, the instantiation will not occur untill the call to MySingleton.getInstance()
But if you put the static MySingleton object as a direct property of the class, instead of inside the enum , it will get instantiated on the call to MySingleton.myTrigger , this is because all static fields are instantiated when the class is loaded.
But in case of enum, enum is not a static property of the class, it is only loaded on access.
I tested something like this as well -
class MySingleton {
public static String myTrigger="a trigger";
private MySingleton(){
System.out.println("Printing");
}
public static enum LazyLoad {
IMDB_LOOKUP_INSTANCE;
public static final String Hello = "Hello";
private static final MySingleton IMDB_LOOKUP = new MySingleton();
}
public static MySingleton getInstance() {
return LazyLoad.IMDB_LOOKUP_INSTANCE.IMDB_LOOKUP;
}
}
In the above , the call to MySingleton.LazyLoad.IMDB_LOOKUP_INSTANCE.Hello would also cause instantiation of MySingleton object.
Your singleton will not get instantiated until you call MySigleton.getInstance().

how java singleton can extends other classes

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;
}
}

Enums and Singletons

Consider the following implementation
public enum Singleton {
INSTANCE;
private final OnlyOne onlyOne;
Singleton() {
onlyOne = new OnlyOne();
}
public static Singleton getInstance() {
return INSTANCE;
}
public static void main(String[] args) {
Singleton one = getInstance();
one.onlyOne.method();
}
}
class OnlyOne {
public void method() {
System.out.println("Hello World");
}
}
Here I have tried to implement the Singleton using enum. I want OnlyOne to have just one instance. My question is how do I restrict clients from instantiating objects of class OnlyOne? Because in some other class we can easily do this
OnlyOne one = new OnlyOne();
I cannot provide a private constructor for it because doing so will break this
Singleton() {
onlyOne = new OnlyOne();
}
Do I need to use the enum as an inner member of OnlyOne class ? Any suggestions?
INSTANCE itself is the singleton. Add your method directly to the enum.
public static void main(String[] args) {
Singleton.INSTANCE.method();
}
public enum Singleton {
INSTANCE;
public void method() {
System.out.println(this);
}
}

Singleton class Identification

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;
}
}

singleton using enum

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

Categories