I've seen this code which has two different way its written
public static void main(String[] args) {
Tester.boot();
new tester();
Tester class:
public static tester instance;
public static void boot() {
if (instance == null)
instance = new tester();
}
public Tester() {
System.out.println("test made");
}
What is the difference beetween tester.boot(); and new tester();
Are there any benefits to either?
There are three concepts being displayed here:
Lazy Initialization
Static
Encapsulation (at least the lack thereof)
Tester class:
if (instance == null)
instance = new tester();
That's used when you wish to control the construction of an object. The variable instance controls if new Tester() will be called by boot().
This can be used to implement Lazy Initialization. That's the practice of delaying construction of an object until it is needed. It's typically used when construction is both expensive and not always needed. Here it is delayed until boot() is called. Lazy Initialization is not only used for singletons. Some believe that using Lazy Initialization in java to create a singleton is actually wrong because of how the class loader works. They claim it's a habit ported over from c++ where it made sense. As a pattern, singleton has been controversial enough that some call it an anti pattern.
Tester class:
public static tester instance;
boot(), constructs a Tester object, sets instance to that object (Note: tester should have been capitalized). The fact that instance, which is of type Tester, resides in theTesterclass means thatTesteris [**self referential**][7], like the nodes in a linked list. But, unlike nodes, becauseinstanceisstatic, allTesterobjects have the same copy ofinstance`.
Because boot never puts what it constructs anywhere but in instance, only one boot() constructed Tester object ever exists at any one time, so long as instance is never copied anywhere. It easily could be, because it's public.
So long as instance is never set back to null boot() will construct a Tester only once no matter how many times it's called. Since instance is public it could be set to null at any time by anything that knows about Tester. Doing so would allow boot() to construct again and the old Tester object would be forgotten (garbage collected).
Since Testers constructors have not been made private there is no guaranty that Tester is never constructed by something other than boot(). That means there could still be many Tester objects running around. But they all have one instance in them that may or may not be themselves.
A classic singleton would have Lazy Initialization, be self referential, and be encapsulated in such a way that at most only one Tester object would ever exist. However, There is nothing here that proves this was meant to be a singleton in the first place. This could be a construction optimization gone horribly wrong.
This is sort of implementation of a SINGLETON pattern, in Java.
Look here to understand the concepts behind this pattern click here.
Shortly, you want to use this pattern if you want to have an instance of the class Instance trough all application's life cycle.
To understand it, the key in your code is in the part "if(instance == null)" {instance should be written with lower key, as it should be a class variable}.
If you go simply with the "new ..." any nuber of instances of this variables could be created.
If instead you use the boot method, you are sure that the instance is always the same.
Anyway in the implementation you have written something is missing.
You should refer to this link, where there is also a complete implementation in Java programming language.
boot is useless, you're not showing how Instance is used. But I think it's there to implement a singleton, meaning to assure that only one instance of the class is created. I don't think it's a good implementation as Instance can be used by mistake without being initialized.
When you write new tester() then you're creating a new instance of tester object.
Please follow Java Naming Convention and rename your variables accordingly.
read this comment to know when it makes sense to have an instance and when not.
To be specific--if you use tester.boot() it would set "instance" properly, if you call the constructor directly, it will not.
This is a really broken version of the singleton pattern, to do it correctly the constructor should be made private which makes new Tester() impossible.
Also, the boot method should look a little more like:
public synchronized static Tester boot()
{
if(instance == null) {
instance=new Tester();
}
return instance;
}
and even that is probably iffy.
Related
In my main class I have public static Pet myPet = new Pet();.
I have another class "Welcome" from which I want to access myPet. I want this object to be used in my whole project (it's a game, swing, and this pet will be the main character). I can use Main.myPet.setName(); but I don't know if it's good practice. This just seems the most natural to me. I don't know if starting new windows and passing it as a parameter is a good solution. Is there any other way to access this object or it'll be fine to leave it like that?
If your object is only going to be used inside of your main method instantiate it as Pet myPet = new Pet();
If you are going to use the object over several methods in your main class declare it as private static Pet myPet = new Pet();
However, I advise you to refrain from instantiating the object as a static instance of a class because it will not allow you to test properly.
If there is ever going to be only one "pet" instance, and you don't intend to implement things like game saving, I see no harm in it.
Static fields may sometimes be considered a code smell (bad practice), but if the application is really simple, it's not a problem and can help readability.
If you plan to add game saving etc, it may be a good idea to have a class representing the game state, and the pet being it's field. Then pass this around, not the pet itself - you may later add more things to the game, and you just add them to the game state class.
Avoid using static variables like this, as this will limit what you can do with the code, including how you can expand it or test it (such as with unit testing). Instead, try to keep most all of your code out of the static world and in the instance world. The main method should mainly be used for setting the actors in position and then starting them up, and little else. Pass references where needed if you need classes to share objects. Most important, and I can't stress this enough, get a good book, or several books, on object-oriented programming principles and study it.
Usually you do it by creating accessors/ mutators( get and set methods) in order not to expose all members to every other object. Therefore pet must be private, or a static variable inside a utility class, also via get and set accessible. Unless there is no real reason for making a member public, avoid it whenever possible. This ensures encapsulation and is a best practice oo Design rule.
You may want to consider changing your class definition of Pet to the singleton pattern, rather than defining it as a static field in your main class. For example:
public class Pet {
private static volatile Pet instance = null;
//other fields for Pet
//Private constructor to prevent instantiation without calling getInstance
private Pet() { }
//getInstance ensures that only a single instance of the Pet class is instantiated
public static Pet getInstance() {
if (instance == null) {
synchronized (Pet.class) {
if (instance == null) {
instance = new Pet();
}
}
}
return instance;
}
//other methods for Pet
}
You could then use this in your main class, or any other class, by using the following line:
Pet myPet = Pet.getInstance();
Calling the static method getInstance for the first time will create a new Pet object, but every time it is called after that it will return the same instance of Pet, essentially creating a globally accessible instance of Pet. However, you should read up on the benefits and drawbacks of using a singleton pattern before using it. The singleton pattern is generally frowned upon, but it can be useful in some situations.
You could extend the welcome class to access the information from your previous class. public class Welcome extends PetmyPet {.
today i have stumbled on a code which i have seen in my project and was worried looking into it. I dont realize why they have made these as static methods as they change state of object within them.
below is the code
#Controller
CruiseController{
getCruiseSearchResults(){
//prepare cruise serach request, static method in CruiseHelper
CruiseSearchRequest cruiseReq = CruiseHelper.prepareRequest();
...futher impl
}
/** my helper class which has utlity methods */
CruiseHelper{
public static CruiseSearchRequest prepareRequest(){
CruiseSearchRequest cruiseRequest = new CruiseSearchRequest();
// all below methods are static
setCruiseTypeandDestination(cruiseRequest)
setStartAndEndDate(cruiseRequest)
setShipAndDeparturePort(cruiseRequest)
setDurationAndAccesiblity(cruiseRequest)
setPromoType(cruiseRequest)
setResultPreferences(cruiseRequest)
return cruiseSearchCriteriaDTO
}
static void setCruiseTypeandDestination(CruiseSearchRequest cruiseRequest){
/** changing the state of object in static method */
cruiseRequest.setCruiseType("ABC");
cruiseRequest.setCruiseType("Alaska");
}
//.... further static methods as above, all of them
//change the state of cruiseRequest
}
So i know that, above methods should not be static as they all have properties of each request. But the code is working and has not failed on any load test performed.
my important question is : "can this above code be considered ??" and "can this fail, if yes. then in what scenario ?"
Indeed, these methods change the state of an object, but it's an object that is given as a parameter to them, which is perfectly valid and makes sense.
static means that the method is bound to the object definition (the class) and not to any specific object instance. Thus static method cannot change the state of it's own object as it simply does not have an instance to work on (it does not have a this).
I suggest you read this about static and class variable : Understanding Class Members
Static methods are used to imply that that method doesn't need an instance of the class to be called. For example consider the String class. It can still change the state of any object.
replaceAll() is not a static method as it needs an instance to work on. where as valueOf() isn't as it doesn't need a String instance.
I suggest you revisit the basics of Java.
I dont realize why they have made these as static methods as they change state of object within them.
Because they're methods of a class called CruiseController. They are modifying instances of a CruiseSearchRequest, a different class. You could not do cruiseSearchRequest.setCruiseTypeandDestination();, because the method setCruiseTypeandDestination isn't on the CruiseSearchRequest class. So, instead, it receives the CruiseSearchRequest object as a parameter, and since it isn't tied to any instance of CruiseController, it is a static method of that class.
You could make the methods non-static if you moved them to the CruiseSearchRequest class. However, you don't need to. There is absolutely nothing technically wrong with modifying objects in a static method. It might or might not be a good design for your particular program, but it will not "fail".
Methods in Spring shouldn't be static not because they won't work but becouse it is a bad decision in terms of your application architecture. Static methods are wrong decision in terms of unit testing - it is harder to mock static methods than objects. Also I think intensive usage of static methods breaks the concept of dependency injection and the code becomes more tightly-coupled. Here is a nice article on this topic.
Is there any method to check whether any instance of a class is running?
I have a GUI and I don't want open another instance of it, if a one is already running.
I know about including a counter in constructor. Any method except that?
Thanks in advance!!
Use the singleton pattern.
Here is a simple implementation in java of a singleton:
public class MyClass {
private static MyClass INSTANCE = new MyClass();
private MyClass() { // private constructor prevents creation outside class
}
public static MyClass getInstance() {
return INSTANCE;
}
}
Note that this is not "bulletproof" (there are "hacks" you can use via reflection to circumvent this and create two instances), however if you're the only user of the code it will be fine.
Is there any method to check whether any instance of a class is running?
The simple answer is No.
The normal way to deal with this problem is to use the Singleton design pattern. The idea of the pattern is that you write the code to remove the possibility of creating multiple instance of the class.
In Java you typically do this by declaring the class constructor to be private, and providing access to the singleton instance via a static method. Depending on your precise requirements, the singleton can be created eagerly or lazily.
Bohemian's answer provides a good example of this approach.
(In Java 5 or later, it is also possible to use enum types to implement singletons.)
Use Enum as recommended by J. Bloch (Effective Java Programming 2nd Ed., Addison Wesley)
I have a singleton class.
When accessing the methods of the class I have the choice of two possibilities.
Create those methods as instance specific and then get the instance and invoke them
Create those methods as static and invoke them and they will get the instance
For example:
Class Test{
private int field1;
Test instance;
private Test(){};
private Test getInstance(){
if (instance == null)
instance = new Test();
return instance;
}
public int method1() { return field1;}
public static int method2() {return getInstance().field1;}
}
Now, elsewhere I can write
int x = Test.getInstance().method1();
int y = Test.method2();
Which is better?
I can think of a 3rd alternative where I use "instance" directly in the static method and then capture the exception if it is null and instantiate it and then re-invoke itself.
I could, in theory, just make the whole lot static.
However, this will create me problems when saving the state at activity close since the serialization doesn't save static.
I think the first one is cleaner.
However, keep in mind that under some extreme cases, Android may kill your static instances. See this for example: http://code.google.com/p/acra/ .
A workaround I've found somewhere for this, is to keep a reference to your singleton from the Application class, as well. I don't know how problem-proof this is, though.
You should avoid making everything static. Some people would even say that a singleton is not done.
The whole point of the singleton pattern is that you can change the implementation. In most cases you use it to keep the possibility open to "hook" in some other implementations of this functionality later.
Read: when deciding in favor of singleton plan for a setInstance method too, not just for a getInstance. - If this does not make sense, just use a plain static class.
In the other hand singletons are out of season, if you want to be hip and all that. Do a search for "eliminating global state". There are some Google-sponsored talks about it too. In short: your code will be more testable and helps you avoid some dependency chaos. (Besides being hip and all, it is definitely a step into the right direction).
In my personal opinion having static methods is bad design in the first place. It, of course, depends on the program itself, but allowing a class to have static method will have impact on the whole design. Some reasoning behind my statement:
If static method can easily change state of some object, sooner or later bugs will emerge
If you publish static method with your program, every client that will use it will have a very strong dependency on your code. If you decide to remove or change this method someday - you will break every single client that used your class.
So, if you can - avoid it.
If, from any reason, you will insist on having static method, I guess the first solution is better. That's how singleton should work. You should obtain a reference to a SINGLETON OBJECT via static method, but this object should be then used according to all principles from Object Oriented Programming.
In a large, complex program it may not be simple to discover where in the
code a Singleton has been instantiated. What is the best approach to keep track of created singleton instances in order to re-use them?
Regards,
RR
A Singleton usually has a private constructor, thus the Singleton class is the only class which can instantiate the one and only singleton instance.
It's the responsibilty of singleton class developer to make sure that the instance is being reused on multiple calls.
As a user, you shouldn't worry about it.
class Singelton
{
private static Singelton _singelton = null;
private Singelton()
{
}
// NOT usable for Multithreaded program
public static Singelton CreateMe()
{
if(_singelton == null)
_singelton = new Singelton();
return _singelton;
}
}
Now, from anywhere in your code, you can instantiate Singelton, how many times you like and each time assign it to different reference. but c'tor is called ONLY once.
I would use an enum
enum Singleton {
INSTANCE:
}
or something similar which cannot be instantiated more than once and globally accessible.
General practice for naming methods which create/return singletons is getInstance(). I don't understand the situation when you can't find the place in code where singletons created, but you can search for this method name.
If you want to catch the exact moment of singleton creation - you can use AOP. AspectJ is a good example in java. You will be able to execute your code before/after creation of class or calling getInstance() method.
If your question is about reusing of created Singletons, then search this site. For example