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 {.
Related
When the Gang of four introduced the singleton pattern, they also had to explain, why not to use static class fields and method instead. The reason was: the possibility to inherit. For Java it had sense - we cannot normally inherit the class fields and methods.
Later the "Effective Java" book appeared. And we know now that the existence of reflection destroys the singularity of the singleton class with private constructor. And the only way to make a real SINGLEton is to make it as a single item of an enumeration. Nice. I had done some myself this way.
But a question remains: While we cannot inherit from enumeration, what is the use of this singleton? Why we don't use these old good static/class fields and methods?
Edit. Thanks to the #bayou.io I see that in https://softwareengineering.stackexchange.com/a/204181/44104 there is a code that can trick the enum, too, and create again two exemplars of the enum singleton. The other problems are mentioned there, too. So, there is no need to use enum instead of the usual singleton class pattern, too? BTW, all enum pluses that are mentioned here till now, work for singleton classes, too.
what is the use of this singleton? Why we don't use these old good static/class fields and methods?
Because enum is an object so it can not only be passed around but also implement interfaces.
Also since we are making a class, we can use the different public/private options available to all kinds of classes.
So in practice, we can make a singleton that implements an interface and then pass it around in our code and the calling code is non the wiser. We can also make the enum class package private but still pass it around to other classes in other packages that expect the interface.
If we used the static methods version, then the calling class would have to know that this object is a singleton, and our singleton class would have to be public so the other classes can see it and use it's methods.
There's nothing particularly wrong with the "good old fashioned singleton", enum "singletons" are just convenient - it saves you the need to muck around with boiler-plated code that looks the same in every singelton.
To me, a singleton makes sense wherever you want to represent something which is unique in its kind.
As an example, if we wanted to model the Sun, it could not be a normal class, because there is only one Sun. However it makes sense to make it inherit from a Star class. In this case I would opt for a static instance, with a static getter.
To clarify, here is what I'm talking about :
public class Star {
private final String name;
private final double density, massInKg;
public Star(String name, double density, double massInKg) {
// ...
}
public void explode() {
// ...
}
}
public final class Sun extends Star {
public static final Sun INSTANCE = new Sun();
private Sun() { super("The shiniest of all", /**...**/, /**...**/); }
}
Sun can use all the methods of Star and define new ones. This would not be possible with an enum (extending a class, I mean).
If there is no need to model this kind of inheritance relationships, as you said, the enum becomes better suited, or at least easier and clearer. For example, if an application has a single ApplicationContext per JVM, it makes sense to have it as a singleton and it usually doesn't require to inherit from anything or to be extendable. I would then use an enum.
Note that in some languages such as Scala, there is a special keyword for singletons (object) which not only enables to easily define singletons but also completely replaces the notion of static method or field.
ENUM singletons are easy to write. It will occupy very less code, which is clean & elegant if you compare with implementation of lazy singleton with double synchronized blocks
public enum EasySingleton{
INSTANCE;
}
Creation of ENUM instance is thread safe.
ENUM singletons handled serialization by themselves.
conventional Singletons implementing Serializable interface are no longer remain Singleton because readObject() method always return a new instance just like constructor in Java. you can avoid that by using readResolve() method and discarding newly created instance by replacing with Singeton
private Object readResolve(){
return INSTANCE;
}
Have a look at this article on singleton
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.
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.
So I have a player class in my game. Logically there only needs to be one player object (single player) But a lot of different classes need access to the player object. (ie, maps needs to know were player is, as does camera and enemies need to interact with the player, etc).
I have a couple of options.
Either I could pass this player object around to everything that needs it which is cumbersome. (Dependency injection I think it's called)
Just make it public static.
Make it a singleton.
What are the pros/cons of each?
I would not use a Singleton or static variable here and instead would hand a Player instance to the classes that need it via setters. If you only need one player instance - only call new Player() once :-)
See my take on Singletons here. Short summary: their typical misuse (avoiding "cumbersome" setters) violates OO and lowers design quality.
Static variables are cut from the same cloth as Singletons, along with the Monostate (non-static getters, static data, constructor is the "factory"). Avoid them. Consider if you made everything static: player, map, camera, enemies, etc. You would avoid a lot of "cumbersome" setters. But is it OO? When you finish your game can you reuse your pathfinding algorithms, AI algorithms, etc. on another game, or do they have too many global variables (Singletons et al) specific to your current game burned into them forever?
So, your options are:
Just make it public static.
Make it a singleton.
Both would effectively turn it into a global variable. I'm not a big fan of globals: they make everything harder to test and debug.
Pros: Easier access
Cons: Very high coupling (what if you want to make it a two player game?); Adds complexity to tests; Changing the player in one place might have unexpected consequences on other places.
I could pass this player object around to everything that needs it which is cumbersome. (Dependency injection I think it's called)
Pros: Lower coupling; Facilitates testing; You can pass copies of the player to other classes and reduce the chances of side-effects.
Cons: Having to pass Player references makes the API a bit more complex, but part of it may be mitigated by using a dependency injection framework, such as Guice.
Apart from teh advantages provided by Java Setter and Getter, I can't really think of any new ones that a singleton pattern (public static Type getInstance()) would give you over public variable (public static Type var).
But in general it's always better (from future pov) to control access to member variables (especially access from outside the class that has this as member variable), so I would recommend a private static variable with a public getter. Which is somewhere between a singleton and a public static var.
Using a singleton gives you the possibility to extend the base class and provide alternative implementations of Player, using a static method does now allow that flexibility.
Another point is that "conceptually" a player is an object and not a class.
I would avoid making it static. You want your code to be reusable and a player is certainly an object that may require several instances in an alternate project.
I would create simple getAttribute(), editAttribute methods that return or edit the attribute I need.
Another option would be to simply make the shareable attributes public within the player class although I would prefer the get/edit methods option.
Singletons can implement interfaces which can be used to refere to the singleton. i.e. you don't need hardcoded references to a singleton throughout your code. This makes unit testing easier, if you want a different instance for testing purposes.
public interface Printer {
public void print(String line);
}
public enum ConsolePrinter implements Printer {
INSTANCE;
public void print(String line) {
System.out.println(line);
}
}
// to print to the screen
Printer printer = ConsolePrinter.INSTANCE;
// for testing purposes.
Printer printer = createMock(Printer.class);