码迷,mamicode.com
首页 > 编程语言 > 详细

单例模式java实现

时间:2014-08-01 12:59:31      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   java   2014   ar   line   

bubuko.com,布布扣

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());
}
}

单例模式java实现,布布扣,bubuko.com

单例模式java实现

标签:style   blog   http   color   java   2014   ar   line   

原文地址:http://www.cnblogs.com/vonk/p/3884554.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!