《疯狂JAVA讲义》——Singleton类

如果一个类始终只能创建一个实例,则这个类被称为单例(Singleton)类。

class Singleton
{
    //使用一个变量来缓存曾经创建的实例,因为该变量需要被静态方法访问
    //所以使用static修饰
    private static Singleton instance;
    //对构造器使用private修饰,对外隐藏该构造器
    private Singleton(){}
    //对外提供一个public方法用于创建该类的对象,因为调用方法之前还存在对象
    //所以调用该方法的只能是类,故使用static修饰
    public static Singleton getInstance()
    {
        //为了保证只产生一个Singleton对象,每次调用都要进行判定
        //若instance为null,则表明还未创建Singleton实例
        //若instance不为null,则返回之前创建的Singleton实例
        if(instance == null)
        {
            //创建一个Singleton实例,并将其缓存起来
            instance = new Singleton(); 
        }
        return instance;
    }
} 

public class SingletonTest()
{
    public static void main(String[] args)
    {
        //创建Singleton实例不能通过构造器
        //只能通过调用getInstance方法
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();
        //因为该类只产生一个实例,所以s1与s2是同一个对象,输出true
        System.out.println(s1 == s2);
    }
}

上述程序在多线程条件下运行会生成多个实例,可以使用synchronized关键字静态内部类的方法实现线程安全的单例模式。

/*synchronized关键字*/
class Singleton
{
    private static Singleton instance = null;

    private Singleton(){}

    private static synchronized void init()
    {
        if(instance == null)
            instance = new Singleton();
    }

    public static Singleton getInstance()
    {
        if(instance == null)
            init();

        return instance;
    }
}

/*静态内部类*/
class Singleton
{
    private static class instanceInit
    {
        private static Singleton instance = new Singleton();
    }

    private Singleton(){}

    public static Singleton getInstance()
    {
        return instanceInit.instance;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值