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;
}
}
Related
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());
}
}
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;
}
}
I am creating a custom class in main application class. Lets say My mainAccount.
Now, i am creating many activities. I want to mainAccount variable in every activity, how can i do that? One way is to put in intent and pass to each activity. Is there any better way, like making it global etC?
Best Regards
Look up Singleton classes. Basically, you want something like this.
public class Singleton {
private static Singleton instance = null;
protected Singleton() {
// Exists only to defeat instantiation.
}
public static Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
Then, for any class that needs access to the class, call:
Singleton var=Singleton.getInstance();
This is essentially global, without most of the negative consequences of global variables. It will ensure that only one object of that class can exist, but everyone who needs it can access it.
Have you thought about using preferences?
A great resource for more info is.
http://mobile.tutsplus.com/tutorials/android/android-application-preferences/
Or you can create a class that extends application as demostrated by
http://www.helloandroid.com/category/topics-covered/global-variables
Just define an Abstract class with those variables and methods whichever you want to access in activities.
For example:
public abstract class BaseActivity extends Activity
{
//static variables
// static methods
}
Now extends this BaseActivity class in your all activity:
public class HelloAndroid extends BaseActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
You can use "singleton" class, or "static" class (if you don't need to initialize it, instantiate or inherit or implement interfaces).
Singleton class:
public class MySingletonClass {
private static MySingletonClass instance;
public static MySingletonClass getInstance() {
if (instance == null)
instance = new MySingletonClass();
return instance;
}
private MySingletonClass() {
}
private String val;
public String getValue() {
return val;
}
public void setValue(String value) {
this.val = value;
}
}
String s = MySingletonClass.getInstance().getValue();
Static class:
public class MyStaticClass {
public static String value;
}
String s = MyStaticClass.value;
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