lundi 17 mai 2021

how to return the number of times Singleton accessed getInstance()?

I want to use a private int type accessCount() to return the times of Singleton has been accessed via the getInstance() method, but always get error. Here's my two piece of code:

ExampleSingleton.java

public class ExampleSingleton {
  private int accessCount;
  private static ExampleSingleton instance = new ExampleSingleton();
  private ExampleSingleton() {
    System.out.println("I, the ExampleSingleton, am being created");
   }
  public static ExampleSingleton getInstance() {
    System.out.println("The sole instance of ExampleSingleton is being retrieved")
    
  }

}

ExampleTest.java

public class ExampleTest {
  public static void main(String[] args) {
    ExampleSingleton s = ExampleSingleton.getInstance();
    System.out.println("The ExampleSingleton has been "
    + "accessed via the getInstance() method "
    + s.accessCount()
    + " time(s)");
    s = ExampleSingleton.getInstance();
    System.out.println("The ExampleSingleton has been "
    + "accessed via the getInstance() method "
    + s.accessCount()
    + " time(s)");
  }
}

So I can get the following output output

Aucun commentaire:

Enregistrer un commentaire