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;
}
}
Related
In my Java program, I am attempting to ensure that only one object of the class "ATM" is created. For this, I have a classic singleton class as below:
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
How do I ensure that only one object of the class ATM is made? E.g. Where do I now put the code:
ATM theATM = new ATM();
Does this code belong in the singleton class, or within the ATM class?
You don't need that Singleton class, because your singleton has to be ATM.
So, just use this in ATM.java:
public class ATM {
private static ATM uniqueInstance;
private ATM() {}
public static ATM getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new ATM();
}
return uniqueInstance;
}
}
Now, you can call your line:
ATM theATM = new ATM();
only if you are in the ATM class itself, because your constructor is private, but this is useless because you care about uniqueInstance in this situation.
If you are in a different class, you should use:
public class Main {
public static void main(String[] args) {
ATM theATM = ATM.getInstance();
}
}
The idea of the singleton pattern is that even if you run again ATM.getInstance();, the same (initial) instance (uniqueInstance) will be returned. If it wasn't initialized before, it is initialized. Otherwise, the old instance is returned. So, this is how you are sure that you won't have multiple instances.
Of course, there are better implementations of the singleton pattern that are thread safe.
E.g.:
thread safe - lazy:
public class ATM {
private static ATM uniqueInstance = null;
private ATM(){}
public static synchronized ATM getInstance() {
if ( uniqueInstance == null ) {
uniqueInstance = new ATM();
}
return uniqueInstance;
}
}
thread safe - eager
public class ATM {
private static ATM uniqueInstance = new ATM();
private ATM(){}
public static ATM getInstance() {
return uniqueInstance;
}
}
thread safe - using enum
public enum ATM {
UNIQUE_INSTANCE;
...
}
Do I have to use private constructor to make a class singleton? Is there any other way than using private constructor?
Can't I make a class singleton using public constructor?
If your class has a public constructor, then anybody can create an instance of it at any time. So it's not a singleton any more. For a singleton, there can exist only one instance.
The reason it has to be a private constructor is because you want to prevent people from using it freely to create more than one instance.
A public constructor is possible only if you are able to detect an instance already exist and forbid a another instance being created.
Is there no way other than using private constructor ? Can't we make a class singleton using public constructor ?
Yes, it is actually possible, for example:
class Singleton
{
private static Singleton instance = null;
public Singleton() throws Exception //Singleton with public constructor
{
if(instance != null)
throw new Exception("Instance already exist");
//Else, do whatever..such as creating an instance
}
}
If you really must use public constructor, then you should check whether instance is null and throw an exception.
if(instance != null)
One way to create Singleton object using public constructor with throw exception from constructor if object is already exist.
For Example:
public class Singleton {
private static Singleton singleton;
private String hello;
public Singleton() throws Exception {
if (singleton != null) {
throw new Exception("Object already exist");
}
}
public static Singleton getInstance() throws Exception {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
public String getHello() {
return hello;
}
public void setHello(String hello) {
this.hello = hello;
}
public static void main(String[] args) {
try {
Singleton single1 = Singleton.getInstance();
single1.setHello("Hello");
System.out.println(single1.getHello());
Singleton single2 = Singleton.getInstance();
System.out.println(single2.getHello());
Singleton single3 = new Singleton();
System.out.println(single3.getHello());
} catch (Exception ex) {
}
}
}
Generally, Singleton pattern is used when you should have exactly 1 object of a class (e.g. Factories are very often implemented as Singletons).
public modifier allows anyone to access your method (as well as your constructor). In that case, anyone can create an instance of your class, thus it won't be a singleton anymore.
By setting private modifier to your constructor, you are sure, it cannot be used outside of the class - no one will create any more objects of that class.
public class SingletonExample {
private static final SingletonExample instance;
// Initialize instance object in static block - done while loading the class by class loader
static {
instance = new SingletonExample();
}
private SingletonExample(){}
public static SingletonExample getInstance(){
return instance;
}
// Method used to create java.test.DateFormat using Oracle SQL Date pattern
public DateFormat createDateFormat(String mask){
if("DD-MM-YYYY HH24:MI:SS".equals(mask)){
return new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
} else if("DD-MM-YYYY".equals(mask)){
return new SimpleDateFormat("dd-MM-yyyy");
} else {
throw new UnsupportedOperationException("Unsupported mask - " + mask);
}
}
}
And usage example
public class SingletonExampleTest{
public static void main(String... args){
java.util.Date date = Calendar.getInstance().getTime();
SingletonExample singleton = SingletonExample.getInstance();
String mask = "DD-MM-YYYY";
DateFormat df = singleton.createDateFormat(mask);
System.out.println(df.format(date));
}
}
The private constructor is a reason, why your class is Singleton.
This Example shows pretty well, how you can use your Singleton class by using getInstance()
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.)
Can someone give me an example of when you'd use a private static field over a private static final field? I struggle to think of an example of when you'd want to declare a private class variable, that was subject to change.
Enter the Singleton pattern:
public class Clazz {
public static void main(String[] args) {
MyObject myObject = MyObject.getInstance();
}
}
class MyObject {
private static MyObject instance;
//I belong to the class, but I need not be created before somebody wants me.
private MyObject() {
}
public static MyObject getInstance() {
if (instance == null) {
instance = new MyObject();
}
return instance;
}
}
Yes.
For example when you want to have a counter variable to count how many objects have been created from a class, you'll make it static - it's associated with the class and not an object, but it's not final since it's changing:
protected static int counter = 0;
//constructor
counter++;
Worth mentioning note:
I didn't mention the Singleton example since if you want to be thread-safe, the variable must be static and final.
i have a util class where which don't have access to session object. i want to initialize this util class only once while login and want to get that instance throughout application.
Here every user need to have his own instance of that util class how to achieve this.
please help me
are you looking for Singleton Pattern ??
private static MyClass instance;
private MyClass(){}
public static MyClass getInstance() {
if (instance != null) {
return instance;
} else {
return new MyClass();
}
}
public static void setInstance(MyClass inst) {
instance = inst;
}
How about using the factory pattern. Then you can pass parameters to the factory method and return a new instance for each user.
I agree with #GanGnaMStYleOverFlow about singleton, but want to provide better version of its implementation:
public class MyClass {
private static MyClass instance;
private MyClass() {}
public static synchronized MyClass getInstance() {
if (instance != null) {
instance = new MyClass();
}
return new MyClass();
}
}
This class cannot be instantiated directly because constructor is private. You cannot create 2 instances of this class because it is managed by getInstance(). This implementation is threadsafe because getInstance() is synchronized.