码迷,mamicode.com
首页 > 其他好文 > 详细

Singleton

时间:2020-03-12 09:23:58      阅读:51      评论:0      收藏:0      [点我收藏+]

标签:err   com   pre   初始化   log   stat   exce   row   single   

public class Singleton {
    private static Singleton singleton = new Singleton();
    private Singleton(){
        System.out.println("生成一个实例");
    }
    public static Singleton getInstance(){
        return singleton;
    }
}
/**
 * 最多生成3个实例,可根据编号获取实例
 */
public class Singleton3 {
    private static Singleton3[] list = new Singleton3[]{ //生成类的实例时被初始化,只会生成一次
            new Singleton3(0),
            new Singleton3(1),
            new Singleton3(2),
    };
    private int id;
    private Singleton3(int id){
        this.id = id;
        System.out.println("生成一个实例:"+id);
    }
    public static Singleton3 getInstance(int id){
        return list[id];
    }

    @Override
    public String toString() {
        return "::"+id;
    }
}
public class Main {
    public static void main(String[] args) throws ParseException {
//        Singleton s1 = Singleton.getInstance();
//        Singleton s2 = Singleton.getInstance();
//        System.out.println(s1==s2);

        for (int i = 0; i < 9; i++) {
            Singleton3 instance = Singleton3.getInstance(i % 3);
            System.out.println(i+":"+instance);
        }
    }
}

Singleton其它用法参考

https://www.cnblogs.com/fly-book/p/10369048.html

https://www.cnblogs.com/fly-book/p/10369046.html

Singleton

标签:err   com   pre   初始化   log   stat   exce   row   single   

原文地址:https://www.cnblogs.com/fly-book/p/12467080.html

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