简体   繁体   中英

Class variables and methods in a singleton pattern implementation

If we have a singleton class, say:

private static Singleton instance = new Singleton();

private Singleton() {

}

public static Singleton getInstance() {
    return instance;
}

Now we want to do the classic work. Add some global variables and methods, to simplify just think about getters. Imagine we need to global variables, say str1 and str2:

This two variables and their getters must be static or the fact that we are forcing this class to be a singleton is enough to ensure that only one instance of the class wil exists?

To be more precise:

   private String str1;
   private String str2;

          VS

   private static String str1;
   orivate static String str2;

           AND

   public String getStr1();
   public String getStr2();

          VS

   public static String getStr1();
   public static String getStr2();

The private constructor will enforce having only one instance at a time. You should still follow standard OOP principles .

private static Singleton instance = new Singleton();

    private Singleton() {

    }

    public static Singleton getInstance() {
        return instance;
    }

    private String str1;
    private String str2;

    public String getStr1() { return str1; }
    public String getStr2() { return str2; }

}

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