I've got quite disturbing problem with singleton in my project.
I created a class called Singleton (how creative) with a variable String name;
Then I created another class called Player where I take a name of user.
And main class where I want to save the data kept in Singleton.
The problem is, it saves name of the user only if I take it in main class..it seems not to work in other classes.
What is the reason ? How to fix it?
Thanks for any advice :)
Here's my singleton class:
private String name;
public void setName(String name) {
this.name = name;
}
public String getName( ) {
return
this.name;
}
private static Singleton instance = null;
protected Singleton() {
}
public static Singleton getInstance() {
if(instance == null)
{
instance = new Singleton();
}
return instance;
}
This is a class where I take a name of a user:
public class NewMain {
public NewMain() {
String u_name="agrfd";
Singleton.getInstance().setName(u_name);
}
}
And here is main class where I would like to save all data from Singleton (here I just try to print it to make sure it works):
public class NewMain1 {
public static void main(String[] args) {
Singleton singleton = new Singleton();
System.out.println(singleton.getInstance().getName());
}
}
You are probably using different instances of Singleton design object. Just use Singleton pattern.
Exemplary implementation:
public class ClassicSingleton {
private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}
Source
Your usage should be:
public class NewMain1 {
public static void main(String[] args) {
new NewMain(); // execute constructor with setter on creation first
System.out.println(Singleton.getInstance().getName());
}
}
Related
I have a singleton class that I would like to mock static methods from, so I can test the functionality of the rest of the class. I have created a simpler example to demonstrate. Assume my class that I want to test is this:
public class MockExample {
private static MockExample instance = null;
private static String ourString = "String from main class";
private MockExample() {
}
public static MockExample getInstance() {
if (instance == null) {
instance = new MockExample();
}
return instance;
}
public String getString() {
return getClassString();
}
private static String getClassString() {
return ourString;
}
}
I am trying to mock out MockExample.getClassString() call, my replacing the method with PowerMockito inside the test. It is important to note that that method is private and only gets called through getString(). My test code, with my static mock is below:
public class MockExample {
private static MockExample instance = null;
private static String ourString = "String from main class";
private MockExample() {
}
public static MockExample getInstance() {
if (instance == null) {
instance = new MockExample();
}
return instance;
}
public String getString() {
return getClassString();
}
public static String getClassString() {
return ourString;
}
}
Online examples suggest that if i get the singleton class after I use PowerMockito.replace(method, stub), than it should call the stub. But in this case it is still calling the original method. I have also tried to "spy", but that is proving to be difficult, since my actual code that I need to mock has arguments. PowerMockito.method() handles those well.
Any help would be greatly appreciated. Thank you.
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;
...
}
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;
}
}
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);
}
}
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;
}
}