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

xxxqqq

  • 博客园
  • 联系
  • 订阅
  • 管理

View Post

Singleton

Singleton is a most widely used design pattern. If a class has and only has one instance at every moment, we call this design as singleton. For example, for class Mouse (not a animal mouse), we should design it in singleton.

You job is to implement a getInstance method for given class, return the same instance of this class every time you call this method.

Example

In Java:

A a = A.getInstance();
A b = A.getInstance();

a should equal to b.

 

 1 class Solution {
 2     /**
 3      * @return: The same instance of this class every time
 4      */
 5     private static Solution instance;
 6 
 7     private Solution(){
 8     }
 9     public static synchronized Solution getInstance() {
10         // write your code here
11         if (instance == null){
12             instance = new Solution();
13             return instance;
14         } else {
15             return instance;
16         }
17     }
18 };

 

posted on 2017-05-10 13:55  xxxqqq  阅读(309)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3