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

Singleton

时间:2016-01-16 07:37:34      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

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.

In Java:

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

a should equal to b.

Challenge

If we call getInstance concurrently, can you make sure your code could run correctly?

 

class Solution {
    /**
     * @return: The same instance of this class every time
/*Singleton类定义一个GetInstance()操作,允许客户访问它的唯一实例。GetInstance()是一个静态方法,主要负责创建自己的唯一实例。*/  */ private static Solution singleton;
//构造方法让其private,这就堵死了外界利用new创建此类实例的可能//  
private Solution(){};

/*此方法是获得本类实例的唯一全局访问点。*/  
public static Solution getInstance() { // /*若实例不存在,则new一个新实例,否则返回已有实例*/   if(singleton==null) { singleton=new Solution(); } return singleton; } };

 

Singleton

标签:

原文地址:http://www.cnblogs.com/kittyamin/p/5134887.html

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