首页 > 代码库 > 单例模式java实现

单例模式java实现

image

package Counter;

public class Counter {
    private int counter;
    private static Counter instance = null;

    protected Counter() {
    }

    public static Counter getInstance() {
        if (instance == null) {
            instance = new Counter();
            System.out.println("New instance created\n");
        }
        return instance;
    }

    public void incrementCounter() {
        counter++;
    }

    public int getCounter() {
        return (counter);
    }
}

 

package Counter;

public class Singleton {
public static void main(String[] args) {
    Counter counter1=Counter.getInstance();
    counter1.incrementCounter();
    counter1.incrementCounter();
    System.out.println("Counter:"+counter1.getCounter());
   
    Counter counter2=Counter.getInstance();
    counter2.incrementCounter();
    counter2.incrementCounter();
    System.out.println("Counter:"+counter2.getCounter());
}
}