• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ForeignStudent
博客园    首页    新随笔    联系   管理    订阅  订阅

单例模式

package com.test;

public class Singleton {

    /**
     * 私有一个静态类为null,返回的时候判断下是否为null
     *         为null说明没有实例,创建一个赋值给静态变量然后返回这个静态变量,
     *         需要的注意的是,是返回这个静态变量,而不是返回创建的实例。
     */
    private static Singleton singleton = null;

    //将构造函数私有化是为了不让其他地方new本类
    private Singleton() {
    }

    /**
     * 单例一般用于线程,所以加上 synchronized 保证统一
     * @return
     */
    public static synchronized Singleton getSingleton() {
        if (singleton == null) {
            singleton = new Singleton();
            //这里需要注意,返回的是成员属性,而不是创建的实例
            return singleton;
        } else {
            return singleton;
        }
    }
}
posted @ 2017-09-25 20:30  ForeignStudent  阅读(119)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3