I have created one Singleton with private constructor and public static method. Now my requirement is, need to create two objects for same class.
First of all, if you are gonna retain more than one instance of the class then you are actually not using Singleton pattern (as pointed out by ANS).
Anyway your question sounds like you need multiple yet limited number of instances of a class. In that case, Object Pool pattern can be useful for you. Please find the wiki link below for your reference (sample java code snippet also found in the same wiki page):
https://en.wikipedia.org/wiki/Object_pool_pattern
If you want to create two instances of a class, then what's the point of creating a singleton class?
Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine.
If you want only two objects to be created, have a static counter to check the number of objects created.. But your class will cease to be singleton.
Related
Whenever we call a constructor in Java, it creates a new object and returns its reference in the end (of newly created object).
Is there any possibility that a Java constructor does not create a new object but return the reference to an already created object?
// Is it possible that myObject is not a new object, its already existing object
MyClass myObject = new MyClass();
I have a list of objects of some class, and based on few parameters in constructor sometimes it more efficient that I don't create a new object, instead I pick up an already existing object. Is there is any other way?
No. Constructors by definition run when a new object is created to initialize it. If the constructor is run, a new object has already come into existence, and there's nothing you can do about it.
What you could do is make a static method which either creates a new object, or returns an existing one. This is the standard approach in such cases.
Say, Boolean.valueOf(boolean value) in the standard library exists for the purpose of avoiding creation of extra objects. You can create them using new Boolean(value), but it is much better to call this method because it will return the same object for the same values.
you cannot do this using constructors but you could use one of the patterns mentioned below.
If you only ever need 1 object then use the Singleton pattern.
If your might have a few variations then use Flyweight pattern as duffymo mentioned.
As duffymo mentions in his comment below - if you using any of these patterns then its important from a concurrency perspective to understand that these objects will be global state - you should therefore ensure they are immutable, and if you cannot make them immutable then you may want to rethink your approach.
No, this is not possible.
JLS section 15.9:
Unqualified class instance creation expressions begin with the keyword new.
An unqualified class instance creation expression may be used to create an instance of a class, regardless of whether the class is a top level (§7.6), member (§8.5, §9.5), local (§14.3), or anonymous class (§15.9.5).
and JLS section 12.5:
A new class instance is explicitly created when evaluation of a class instance creation expression (§15.9) causes a class to be instantiated.
...
Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object using the following procedure: [...]
Notice that this clearly mentions creation of objects and not a possibe re-utilization.
On the other hand, you could create a static factory for your object that uses a pool. You could take a look at the implementation of Integer.valueOf(i) for example. Refer to this answer for example.
You cannot achieve this with just a constructor in Java.
If required, such a behaviour is achieved by using either static method inside the class (like Integer.valueOf(0)) or the whole dedicated object of the different class (like DocumentBuilderFactory) to return the instances. This provides enough control to substitute the existing object instead of always creating a new one.
As a rule, such objects should be immutable and thread safe to be easily shareable. Also, instance reuse and sometimes caching is implemented along these lines.
No. Class provides the blueprint for objects, when using the new operator it is followed by a call to a constructor, which initializes new object.
Source.
If you wish to reuse objects for any reasons you may want considering implement the Flyweight pattern as well as the Factory pattern into your project for best result.
No it's not possible. Create a static method to create objects based on required logic and don't forget to make constructor private.
I am not looking for what is a singleton. There are hundreds of links out. I have not found good examples of client of singleton. Example consider a Singleton class ( whose internals are not important at all)
I want to use this object. Where / how woud client use it ? Should it be used in a constructor ? static initializer ?
Singleton tmp = Singleton.getInstance( );
I would appreciate any sample examples of singleton clients ??
The Singleton Pattern is when you create an object that is designed that there be a single instance of that object in the program. As a client, you have to get a pointer to an instance. You have only four options:
Hold a reference in a static variable and initialize by 'lazy evaluation' that is, test for null, and then initialize when null. After that the value is set.
Hold a reference in a static variable and initialize at static initialization time. Are you sure that the singleton it ready at that time? This is a concern.
Hold reference in local variable, and initialize every time with call to getInstance().
Don't use a variable at all and call in the method chain. If only one reference for one call is needed, this is fine.
In general, getInstance should be quite efficient, and there should be little reason to hold a copy of the reference in your own static. In a sense, your static is duplicating the job of the singleton class which also has to have a static. A single shouldn't ever change, but if it ever did, you would be left holding a stale reference. Option 4 is OK if you need only one call, but this pattern encourages inefficiency when multiple calls are needed. So, for all these reasons I believe you should use option 3 and get the instance every time.
There are times that this singleton pattern is appropriate. There are also times that it is not appropriate, and a class with static methods is more efficient. How can you tell when and when not to use the Singleton pattern? Here is a blog post I made last week on the subject:
http://agiletribe.purplehillsbooks.com/2013/10/08/dont-abuse-singleton-pattern/
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between static class and singleton pattern?
Why would one ever require one and only one instance? Same purpose can be achieved using classes with static member variables and static methods.
As far as I can find out, there might be two possible answers to it -
When your class needs to have state and you want only one object of it. From the design point of view, class with static methods & variables are considered to be the Utility classes and shouldn't be keeping any state.
If your class needs to take part in polymorphism and you want only one object of the class(es) which are in the inheritance tree.
It would be really helpful if someone can provide an example from real life scenario or from any Java API where Singleton objects need to participate in Polymorphism / Inheritance?
Collections.emptySet() is a typical example of a singleton that can't be implemented as a static class since, obviously, its goal is to be an instance of the java.util.Set interface. It's not costly to create, but it would be stupid to create a new instance each time an empty set is needed, since the unique instance can be reused.
Classes that perform logging or common access to data bases frequently follow the Singleton pattern. Basically anything that should have instance methods and that is costly to construct.
Scope and behavior are different concerns and should NOT be mixed. You may want your object to be available per use, per thread, per web request, per session or global (Singleton). The reasons for making these adjustments are likely due to resource management and ultimately performance. The behavior inside your class shouldn't have to change if you change its scope.
Singleton is pattern for taking a regular object and controlling its scope with just a little bit of bolt-on code. Ideally though, you really shouldn't really deal with scope at all inside your object and delegate that to a factory or container.
My answer is quite short but it's enough to use exactly common singleton instead of it's static implementation. The answer is:
Popular paradigm (yes it is!)
Threads (synchronization etc.)
Interface implementation (your static class has some restrictions)
I am developing a Java Program, I have 2 different classes that need to share variables with each other. So for this purpose I created a third class, which contains these shared variables. Basically, first class has its own flag in this third class, and second class has its own flag in this third class. And I add "extend ThirdClass" to other classes' definition, of course.
My problem is when I change the value of first class' flag in the first class' main method, second class is not able to see this change. Namely, it sees the flag with inital value.
I think this is about static variables. But I do not know the solution.
Actually, I have two servers and multi clients. I am trying to simulate differenet situations of these servers for my distributed systems course. Each server has its own data table that is synchronized with other. By simulation, I mean server may be down or up, and when client try to reach down server I need to direct it to other server. So, between clients and servers I need to send information.
How can I share variables between two classes, and easily modify these variables by any class without loss of previous modifications ?
Thank you.
EDIT -- this answer is for a previous version of the question, that does not include anything about clients and multiple servers. This answer is about sharing data between instances of classes.
There are many ways to do something like this. If I understood your approach outlined in the first paragraph, you dont want class1 and class2 to extend class3. You want them to both have a reference to the same instance of class3. If they share a reference to the same object, then changing values on that object will be reflected in both classes. If they extend class3, like you said you tried, then both class1 and class2 will have the properties of class3, but they wont be sharing any data. If class 3 had a property
Object value;
then instances of class1 and class2 would have separate references to separate instances of 'value'.
You need to undertand the relationship between a class, and object instance, and what extending a class means.
Note that this is not really a good way to share information between objects in a real program. You can run into all sorts of concurrency issues. The same is true for a solution that used a global mechanism implemented using static fields.
To do this with static fields do something like:
class SharedData {
public static Object shared1;
}
and then in your class1 and class2 instances you can access
SharedData.shared1
for either set or get.
But I would not do anything like this in any sort of professional context.
You could solve this using statics if it makes sense. When a member is declared static for a class, everyone accessing that member refers to the same instance of that variable, but that doesn't really sound like what you're looking for.
If you want some data to be shared by two classes, you can put the data in a third class and when you create an instance of that third class, be sure the other two classes simply have access to it.
Could you outline what you're trying to accomplish?
I have never found good answers to these simple questions about helper/utility classes:
Why would I create a singleton (stateless) instead of using static methods?
Why would an object instance be needed if an object has no state?
Often, singletons are used to introduce some kind of global state to an application. (More often than really necessary, to be honest, but that's a topic for another time.)
However, there are a few corner cases where even a stateless singleton can be useful:
You expect to extend it with state in the foreseeable future.
You need an object instance for some particular technical reason. Example: Synchonization objects for the C# lock or the Java synchronized statement.
You need inheritance, i.e., you want to be able to easily replace your singleton with another one using the same interface but a different implementation.Example: The Toolkit.getDefaultToolkit() method in Java will return a singleton whose exact type is system dependent.
You want reference equality for a sentinel value.Example: DBNull.Value in C#.
I could see a case for a stateless singleton being used instead of a static methods class, namely for Dependency Injection.
If you have a helper class of utility functions that you're using directly, it creates a hidden dependency; you have no control over who can use it, or where. Injecting that same helper class via a stateless singleton instance lets you control where and how it's being used, and replace it / mock it / etc. when you need to.
Making it a singleton instance simply ensures that you're not allocating any more objects of the type than necessary (since you only ever need one).
Actually i've found another answer not mentionned here: static methods are harder to test.
It seems most test frameworks work great for mocking instance methods but many of them no not handle in a decent way the mock of static methods.
In most programming languages classes elude a lot of the type system. While a class, with its static methods and variables is an object, it very often cannot implement an interface or extend other classes. For that reason, it cannot be used in a polymorphic manner, since it cannot be the subtype of another type. For example, if you have an interface IFooable, that is required by several method signatures of other classes, the class object StaticFoo cannot be used in place of IFooable, whereas FooSingleton.getInstance() can (assuming, FooSingleton implements IFooable).
Please note, that, as I commented on Heinzi's answer, a singleton is a pattern to control instantiation. It replaces new Class() with Class.getInstance(), which gives the author of Class more control over instances, which he can use to prevent the creation of unneccessary instances. The singleton is just a very special case of the factory pattern and should be treated as such. Common use makes it rather the special case of global registries, which often ends up bad, because global registries should not be used just willy-nilly.
If you plan to provide global helper functions, then static methods will work just fine. The class will not act as class, but rather just as a namespace. I suggest, you preserve high cohesion, or you might end up with weirdest coupling issues.
greetz
back2dos
There is a trade-off between using which one. Singletons may or may not have state and they refer to objects. If they are not keeping state and only used for global access, then static is better as these methods will be faster. But if you want to utilize objects and OOP concepts (Inheritance polymorphism), then singleton is better.
Consider an example: java.lang.Runtime is a singleton class in java. This class allows different implementations for each JVM. The implementation is single per JVM. If this class would have been static, we cannot pass different implementations based on JVM.
I found this link really helpful: http://javarevisited.blogspot.com/2013/03/difference-between-singleton-pattern-vs-static-class-java.html?
Hope it helps!!
Singleton is not stateless, it holds the global state.
Some reasons which I can think of using Singleton are:
To avoid memory leaks
To provide the same state for all modules in an application e.g database connection
For me "Want Object State use Singleton, Want Function use static method"
It depends on what you want. Whenever you want the object state (e.g. Polymorphism like Null state instead of null, or default state), singleton is the appropriate choice for you whereas the static method use when you need function (Receive inputs then return an output).
I recommend for the singleton case, it should be always the same state after it is instantiated. It should neither be clonable, nor receive any value to set into (except static configuration from the file e.g. properties file in java).
P.S. The performance between these 2 are different in milliseconds, so focus on Architecture first.
According to GoF’s book Design Patterns, chapter ‘Singleton’, class operations have the following drawbacks compared to singletons (bold emphasis mine):
More flexible than class operations. Another way to package singleton’s functionality is to use class operations (that is, static member functions in C++ or class methods in Smalltalk). But both of these language techniques make it hard to change a design to allow more than one instance of a class. Moreover, static member functions in C++ are never virtual, so subclasses can’t override them polymorphically.