简体   繁体   中英

How do i make a constant-like instance of class in Java?

I am trying to write a simple game, and in that game, there is a class called Fighter , and instances of that class can attack other instances.

I want to make an instance of that class that is always defined and has special properties(i know how to do that please don't try to answer that) so that it can be used as a power player of some sort.

What you probably want is:

public class Fighter {
    public static final Fighter ADMIN_FIGHTER = new Fighter(whatever-args ...);

you can use Singleton pattern like this

public final class AdminFighter {
   private static final AdminFighter instance = new AdminFighter();
   private AdminFighter(){}
   public static AdminFighter instance() {
       return instance;
   }
}

so whereever you are in the project you can use like this

AdminFighter constant = AdminFighter.instance();

and this always return the same instance of AdminFighter like a constant.

NOTE: avoid global constants like this example, they will turn in future headaches and they are sign of poor design. There are tons of blog post discussing about this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM