您的位置:首页 > 其它

题目:单例

2015-08-19 19:03 363 查看
单例 是最为最常见的设计模式之一。对于任何时刻,如果某个类只存在且最多存在一个具体的实例,那么我们称这种设计模式为单例。例如,对于 class Mouse (不是动物的mouse哦),我们应将其设计为 singleton 模式。

你的任务是设计一个
getInstance
方法,对于给定的类,每次调用
getInstance
时,都可得到同一个实例。

您在真实的面试中是否遇到过这个题?

Yes

哪家公司问你的这个题?
Airbnb
Alibaba
Amazon Apple
Baidu Bloomberg
Cisco Dropbox
Ebay Facebook
Google Hulu
Intel Linkedin
Microsoft NetEase
Nvidia Oracle
Pinterest Snapchat
Tencent Twitter
Uber Xiaomi
Yahoo Yelp
Zenefits
感谢您的反馈

样例

在 Java 中:

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

a 应等于 b.

挑战

如果并发的调用 getInstance,你的程序也可以正确的执行么?

标签 Expand

LintCode 版权所有

面向对象设计

相关题目 Expand

2
(oo-design)
中等 赋值运算符重载 20 %

饿汉式AC代码:
class Solution {

/**

* @return: The same instance of this class every time

*/

private static Solution solution ;

public static Solution getInstance() {

// write your code here

if(solution==null){

solution = new Solution();

}

return solution;

}

};

懒汉式AC代码
class Solution {

/**

* @return: The same instance of this class every time

*/

private static Solution solution = new Solution();

public static Solution getInstance() {

// write your code here

return solution;

}

};
另外参考别人代码所写的,多线程 方式

class Solution {

/**

* @return: The same instance of this class every time

*/

private static Solution solution ;

public static Solution getInstance() {

// write your code here

if(null==solution){

synchronized(Solution.class){

if(null==solution){

Solution tmp = solution;

if(null==tmp){

synchronized (Solution.class) {

tmp = new Solution();

}

}

solution = tmp;

}

}

}

return solution;

}

};


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: