由买买提看人间百态

topics

全部话题 - 话题: singleton
1 2 3 4 5 6 7 8 9 10 下页 末页 (共10页)
l********y
发帖数: 1327
1
来自主题: JobHunting版 - singleton哪种写法好?
一种是直接返回reference,一种是返回pointer,请问各位大侠哪个写法好?还是都行
?谢谢
class singleton{
singleton(){}
singleton(const singleton&);
singleton& operator=(const singleton&);
~singleton();
public:
singleton& getInstance(){
static singleton s;
return s;
}
};
class singleton{
singleton(){}
singleton(const singleton&);
singleton& operator=(const singleton&);
~singleton();
static singleton * s;
public:
singleton * getInstance(){
s = new singleton();
return s;
}
};
b********e
发帖数: 693
2
来自主题: JobHunting版 - C++ Singleton的实现
那位大牛能给个C++ Singleton的实现? 我自己写了一个不知道正确与否, 如果希望做到
thread-safe, 应该在什么地方加入mutex和condition variable
class Singleton{
Singleton();
~Singleton();
Singleton(const Singleton &);
Singleton & operator=(const Singleton &);
static Singleton * myinstance;
public:
static Singleton & CreateInstance();
static void Destory();
};
Singleton::Singleton(){
}
Singleton::~Singleton(){
}
Singleton & Singleton::CreateInstance(){
if(!myinstance){
l********n
发帖数: 54
3
来自主题: JobHunting版 - C++ Singleton的实现
class Singleton
{
private:
static Singleton* _instance;
Singleton() {}
~Singleton() {}
Singleton(const Singleton &);
Singleton& operator=(const Singleton&);
public:
static Singleton &getInstance();
static void clearInstance();
};
Singleton& Singleton::getInstance()
{
pthread_mutex_lock(&mutex);
if (!Singleton::_instance)
{
Singleton::_instance = new Singleton();
}
pthread_mutex_unlock
s******e
发帖数: 493
4
来自主题: Java版 - 关于singleton
Basically there are three ways to create singleton: lazy init, eager init
and holder pattern.
Both of eager init and holder pattern depend on JVM class loading process to
guarantee the singleton. The holder pattern was introduced in trying to
avoid
creating a singleton unnecessarily in the case of the eager
initialization.
For lazy init, no matter using doubly checked lock or not, you can both
create a singleton if you use it correctly. The reason trying to introduce
doubly checked lock was to r... 阅读全帖
e******d
发帖数: 310
5
来自主题: Programming版 - A question about singleton
In the following code for Singleton, why will the destructor be
called again and again??
Thank you.
=============================
#include "stdio.h"
class Singleton
{
public:
static Singleton* create_obj();
~Singleton()
{
printf("Destor is called \n");

if(psig != NULL)
delete psig;
}
private:
Singleton() { printf("Contor is called \n"); }
static Singleton* psig;
};
Singleton* Singleton::psig = NULL;
Singleton* Singleton::create_
v*******7
发帖数: 187
6
来自主题: JobHunting版 - singleton pattern problem
I forgot, but some how it should be like this:
class Singleton{
public:
static Singleton * getInstance() {
if (_instance == NULL) {
_instance = new Singleton;
}
return _instance;
}

private:
static Singleton _instance;
Singleton();
~Singleton();
}
I forgot the details, but I think the above is the main idea of Singleton.
w****a
发帖数: 710
7
二爷抬举了,我不是大牛、、、
我觉得singleton在C++里面有几个要注意的。别的语言我也不熟悉就不说了。
一个是跨dll的链接问题。如果是模板的singleton那种继承下来那种,比如
class foo: public singleton
这样的,继承下来的时候注意要显示的声明一下singleton的getInstance之类的函数。
否则跨dll可能会报链接错误。
一个是singleton的生命周期管理问题。就是注意初始化释放的顺序别弄乱了。有些大
型程序,比如说很多个manager,都是以singleton的形式搞的,初始化和释放顺序要自
己手动把握好。
一个是多线程下的singleton问题了。getInstance的时候搞个锁就行。
还有没有大牛有其他的建议?
s*******e
发帖数: 174
8
方法1:
最简单的 public static synchronized getInstance()
方法2:
一次面试中,面试官让我再举出一种方法,我取出了用 inner class 的方法, 以前在
wiki 上看到的:
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
http://en.wikipedia.org/wiki/Singleton_pattern
但是面试官说这种方法是错的~~~~~~~~
方法3:
貌似还有一种方法是:
public class Singleton {
public final static Singleton INSTANCE = new Singleton();
private Singleton() {
e****e
发帖数: 418
9
来自主题: JobHunting版 - 关于singleton 的面试题
public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton() {}
/**
* SingletonHolder is loaded on the first execution of Singleton.
getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
Since Java dynamic loading, wh
T*****e
发帖数: 361
10
According to Head First's Design Pattern, #1 has a performance issue (I
guess this is the point of the above gurus) and can be modified into:
public class Singleton {
___ private volatile static Singleton s;
___ private Singleton() {}
___ public static Singleton getInstance() {
___ ___ if (s == null) {
___ ___ ___ synchronized (Singleton.class) {
___ ___ ___ ___ if (s == null) s = new Singleton();
___ ___ ___ }
___ ___ }
___ ___ return s;
___ }
}
Key points:
1. Lazy initialization
2. volatile
3.
p*****d
发帖数: 80
11
来自主题: Programming版 - c++ singleton questions
singleton
1. ctor: 必须private
否则会允许出现多个instance,这个和singleton的定义矛盾。而且必须定义无参数的ctor,否则编译器默认会定义一个。
2. get_instance method:必须static
否则无法在没有singleton instance的情况下调用产生第一个也是唯一一个instance。
3. copy ctor:必须private
否则下面的语句会出现两个instance
S *s = S::get_instance();
S s1(*s);
4. assignment optr:不必private
因为不会出现第二个instance,所以编译器默认生成的assignment operator只能自己assign自己,无效果。
5. dtor:看情况
dtor可能是有用的,如果允许用户自己释放singleton的话,因为singleton的定义
是无论何时在系统中最多有一个instance存在,可以是1个也可以是0个。但通常是定义一个release函数来free分配的内存而不是使用dtor。但即使dtor是public... 阅读全帖
p*****d
发帖数: 80
12
来自主题: Programming版 - c++ singleton questions
singleton
1. ctor: 必须private
否则会允许出现多个instance,这个和singleton的定义矛盾。而且必须定义无参数的ctor,否则编译器默认会定义一个。
2. get_instance method:必须static
否则无法在没有singleton instance的情况下调用产生第一个也是唯一一个instance。
3. copy ctor:必须private
否则下面的语句会出现两个instance
S *s = S::get_instance();
S s1(*s);
4. assignment optr:不必private
因为不会出现第二个instance,所以编译器默认生成的assignment operator只能自己assign自己,无效果。
5. dtor:看情况
dtor可能是有用的,如果允许用户自己释放singleton的话,因为singleton的定义
是无论何时在系统中最多有一个instance存在,可以是1个也可以是0个。但通常是定义一个release函数来free分配的内存而不是使用dtor。但即使dtor是public... 阅读全帖
s****e
发帖数: 75
13
来自主题: JobHunting版 - 问一个thread safe singleton的问题
看careercup上实现thread-safe singleton:
class Singleton{
private:
static Lock lock;
...
};
Lock Singleton::lock;
T * Singleton::Instance(){
if(object == 0){
lock.Acquirelock();
if(object == 0) {
object = new T;
}
lock.ReleaseLock();
}
return object;
}
请问可不可以把Instance函数写成这样的?不管三七二十一先锁起来再来判断
T * Singleton::Instance(){
lock.AcquireLock();
if(inst == 0) {
inst = new T;
}
lock.ReleaseLock();
return inst;
}
多谢大家指点。
m******t
发帖数: 2416
14
The subject is wrong to begin with. The plain vanilla singleton
pattern doesn't have to do with thread-safety whatsoever, because
it's as simple as:
public class Singleton {
....private static final Singleton INSTANCE = new Singleton();
....private Singleton() {}
....public static getInstance() { return INSTANCE; }
}
The part where we put the initialization into getInstance() is
called Lazy Initialization, which is a separate pattern. And that's
where thread-safe might be a concern - only when r
s*******e
发帖数: 174
15
方法1:
public class Singleton
{
private static Singleton INSTANCE = null;
private Singleton() {}
public static synchronized Singleton getInstance()
{
if(INSTANCE == null)
INSTANCE = new Singleton();
return INSTANCE;
}
}
1 和3 还是有区别的吧,3 没用 Synchronized keyword.
嗯,我已经找到了
z****e
发帖数: 54598
16
来自主题: Java版 - 关于singleton
看到其它版面有人说这个pattern
单独拿出来说说我的两分钱
就我个人而言,我觉得这个pattern可以说是最简单
但是也可以说是最难的一个
因为陷阱太多,可松可紧,牵涉面很广,不少还是冷僻的东西
大概数了数
应该有8种方式
一个一个说
第一种,static instace = new Instance();
这种其实也是最常用的方式,eclipse上可以点击实现
不再赘述
第二种,enum{SINGLETON}
这种是现在比较流行的方式,大多数面试的人其实也就是问这种
这个好处在于连Serializable都实现了,坏处在于无法extends
下面这个是痛苦的开始
第三种,double check
这一种是最难的,要理解其背后的原因,需要深入多线程和byte code的实现中去
无论怎么check,jvm规范都不会阻止说把赋值操作提前
最后要用volatile干掉jvm尤其是jit的优化机制,才能保证在synchronized的时候
不会出现subtle多线程的冲突问题,灰常恶心,甚至测试中都都很难重现这种问题
面试时候如果出这种题,那就是纯粹刁难,move on吧
这已经不是一般... 阅读全帖
z****e
发帖数: 54598
17
来自主题: Java版 - 关于singleton
关于double check,有一个优化版
这个优化版的问题可不是那么简单的
public static Singleton getInstance()
{
if (instance == null)
{
synchronized(Singleton.class) {
Singleton inst = instance;
if (inst == null)
{
synchronized(Singleton.class) {
inst = new Singleton();
}
instance = inst;
}
}
}
return instance;
}





t*********e
发帖数: 630
18
来自主题: Java版 - Singleton Session Bean
一个简单的 demo, 就这一个 class, as a singleton session bean. 然后就是 JSF
中直接对它的引用。 分别点击 Increment, A and B 可分别加 1. 如果去掉
Singleton annotation, 则 click 无效, counter 不增加,A & B 的值一直呆在 1
不变.
这是什么原理? 另外,去掉 @Singleton, Counter 是不是就变成了一个 stateful
session bean.

Counter A#{counter.a}
<... 阅读全帖
t*********e
发帖数: 630
19
来自主题: Java版 - Singleton Session Bean
这是 Wildfly 8 里面的例子,还是最新的东西。是,需要并发控制,上面的 code, 等
同于下面的 version. 默认情况下,容器自动加写锁。
session bean 的概念,包括 stateful, stateless, singleton 还是要搞董吧。在同
一个页面,同一个 browser session, 同一个 client, 每单击 “Increment” 一次,
难道这属于多客户的并发访问? JEE 7 Doc:
"A singleton session bean is instantiated once per application and exists
for the lifecycle of the application. Singleton session beans are designed
for circumstances in which a single enterprise bean instance is shared
across and concurrently accessed by clients."
在 JEE 里,如果要... 阅读全帖
S**********n
发帖数: 250
20
来自主题: JobHunting版 - C++ Singleton的实现
大致写了个思路如下。不想写实现。这里写code太不好看了。
class Singleton
{
public:
static Singleton* getSingleton();
private:
Singleton();
static Singleton* ptr;
};
g*****g
发帖数: 34805
21
来自主题: Java版 - Singleton vs. static class?
讨论一下这个问题,用一个singleton和用一个所有成员都是静态的类,
有哪些pros/cons。感觉上singleton可以实现interface,而静态类不行,
所以singleton在decouple和dyna binding上可能灵活一些。但如果我
只有一个实现呢?
比如我要做一个web service, 这个service接口很简单。类似于
Object process(int ID, Object input)
给个ID,去数据库里去取点相应数据,对input做处理然后输出。
我可以写一个bean实现这个方法, 用spring让它成为singleton来干这个活。
我也可以写一个bean,套接调用一个静态方法来干这个活。
有什么区别吗?
s******n
发帖数: 876
22
#3 is simple, direct, efficient, and correct.
Then why would people bother to invent alternative methods?
The argument is that #3 could have the singleton instance created before
anybody asks for it. One could be referencing some other stuff in the class,
and that triggers the initialization of the class, hence the creation of
the singleton - which could be unwanted at that point.
This argument is very weak. A singleton class is designed to serve its
features through the singleton instance, it i
w*******e
发帖数: 285
23
来自主题: Programming版 - 请问关于c++实现singleton的问题?
【 以下文字转载自 JobHunting 讨论区 】
发信人: windforce (大怪兽), 信区: JobHunting
标 题: 请问关于c++实现singleton的问题?
发信站: BBS 未名空间站 (Sun Nov 16 06:56:48 2008), 转信
我觉得目标和方法是不是差不多这样?
public static的getinstance function返回唯一的instance。
declare private的ctor,copy ctor和copy assignment防止私自创建和copy。
只在第一次调用getinstance的时候才创建对象,所谓的laziness。
在创建instance的时候用mutex同步,但是以后就不用同步提高效率。
我写了一个如下,我觉得运行起来还可以,大家看看有什么问题吗?
class Singleton
{ public:
static Singleton* GetInstance();
~Singleton() {cout << "Dtor"<< endl;};
vo
e******d
发帖数: 310
24
来自主题: Programming版 - A question about singleton
Thank you so much for your explanation.
one line for creating obj is missing in the main function. But the wrong
code gives me an opportunity to learn some new stuff.
In the original code,
1. psig1 is null, but it calls ~Singleton() sucessfully, why? I am just
wondering if the reason is that ~Singleton() is a static function.
2. In the main function, we did not create any Singleton obj, so static
member psig should be NULL,
when ~Singleton()is called, "delete psig" should not be executed. and
H*M
发帖数: 1268
25
来自主题: JobHunting版 - how to create thread-safe singleton?
Not to prevent creating multple copies of singleton(for that we will use mu
tex for that instance method or eager initilization).
By thread-safe, I mean, after the singleton is created. Two threads want to
access it and modify some data within it. It has to be synchronized right? T
hen we use mutex for each "modifying" method of this Singleton class?
t**g
发帖数: 1164
26
来自主题: JobHunting版 - 请问:什么情况下singleton will fail?
一道面试题:
3. Write a sample code to implement the Singleton pattern.
Was asked under what circumstances the Singleton will fail
(copy constructor also needs to be private, etc).
如果把ctor, copy ctor, =operator全都disallowed
那么singleton还能fail么?
w*****e
发帖数: 158
27
来自主题: JobHunting版 - 关于singleton 的面试题
看大牛的面试经历中写道 “面试中问道了设计模式, 但是只谈了singleton,
singleton谈了很多,
如何实现, 有什么问题”
我对于 singleton (classA) 实现的理解:
1. private constructor
2. define static member pointer variable (pointing to an instance of the
classA)
3. define static member function getInstance() returning the pointer or
reference
4. Inside the getInstance():
* when first time class, create an instance and save the address into
static member pointer;
* return the the static member variable
还有什么需要注意的吗? 可能会遇到什么问题?
先多谢了。
M******q
发帖数: 94
28
来自主题: JobHunting版 - 关于singleton 的面试题
"doesn't make a difference" means "it doesn't matter".
singleton doesn't require dctor to be private. singleton's essential idea is
, there is only one instance of a certain class. My understanding is, other
aspects could vary on different variants of singleton.
BTW, destroy() should be static function, not associated with any instance.
g**e
发帖数: 6127
29
singleton这种anti-pattern的东西还是少用。
银行的人喜欢让你实现thread safe lazy initialization singleton,已显摆他们知
道double checked locking. IT公司面试我被问过singleton的缺点是什么,我觉得这
个题更好

modifier
g**e
发帖数: 6127
30
真正意义上(比如java class loader level)的singleton的需要非常非常少。大部分都
可以用spring dependency injection.
缺点么,给singleton写个unit test看看?global variable总的来说越少越好。加一
堆lock影响性能。另外spring inject的java ben默认就是singleton (
ApplicationContext level)

们知
得这
g**e
发帖数: 6127
31
来自主题: Java版 - Singleton
这几天翻effective java, josh bloch推荐了一个enum singleton的写法,他提到
"it is more concise, provides the serialization machinery for free, and
provides an
ironclad guarantee against multiple instantiation, even in the face of
sophisticated
serialization or reflection attacks. While this approach has yet to be
widely
adopted, a single-element enum type is the best way to implement a
singleton."
但是这个不是lazy的
public final class SingletonEnum {
public enum enumSingleton {
INSTANCE;
... 阅读全帖
z****e
发帖数: 54598
32
来自主题: Java版 - 关于singleton
对啊,所以说是multiton啊
只不过这个可能性灰常小罢了
比起第一个不加出现瓶颈的情况来说
当然还不如用第二种
不是singleton就不是咯
没啥大不了的
这其实有个优先级排序
第一不能防止出错,所以必需加volatile
第二要保证优化内存使用同时不能牺牲其它性能
synchronized必需慎重使用,否则情愿不用singleton
第三才是singleton
显然第二个check优先级是最低的
g*****g
发帖数: 34805
33
来自主题: Java版 - 关于singleton
If you are writing a spring app or guice app, it's no brainer which way you
should go. Otherwise you choose the way you most comfortable with.
I don't like a supposed singleton not singleton in marginal scenario. An OK
case today may be a nightmare case when getting extended, and the maintainer
won't necessarily know the limitation of your "singleton".
p****d
发帖数: 2183
34
来自主题: Programming版 - singleton 中的 inner class
在一个singleton中有内部类,继承父类,那么这个singleton 中的 innerclass实例化
的时候也是singleton么?还是我可以在有多个这种innerclass的实例?
X****r
发帖数: 3557
35
来自主题: Programming版 - singleton 中的 inner class
singleton is a design pattern, not a language constraint. You make it
singleton, then it is. It really depends on why you sub-class the singleton
class in the first place.
g*******e
发帖数: 3013
36
来自主题: Programming版 - c++ singleton questions
singleton就是singleton,咋还copy constructor。copy 出 double singleton? :)
getInstance不static没法call啊。:(
g*******e
发帖数: 3013
37
来自主题: Programming版 - c++ singleton questions
singleton就是singleton,咋还copy constructor。copy 出 double singleton? :)
getInstance不static没法call啊。:(
g**e
发帖数: 6127
38
multithreading may cause problems if the singleton class is not property
locked/synchronized.
java reflection can break down the singleton pattern.
f*********5
发帖数: 576
39
来自主题: JobHunting版 - C++ Singleton的实现
static Singleton & CreateInstance();
==>
static Singleton * CreateInstance();

做到
a****n
发帖数: 1887
40
来自主题: JobHunting版 - 关于singleton 的面试题
double check 主要是为了减少多线程情况下进入critical section的次数
static Singleton* getInstance()
{
if (instance == null)
{
lock()
if (instance == null)
instance = new Singleton();
unlock()
}
return instance;
}
s**x
发帖数: 7506
41
来自主题: JobHunting版 - 关于singleton 的面试题
can u do somthing like this?
static Singleton* getInstance()
{
static Singleton s;
return &s;
}
I think i got asked this once, kind of confused. looks like should be okay.
e*****t
发帖数: 1005
42
Simply making the object be a static memeber variable of the class, and
that is the norm of writing a singleton class.
The object is referenced by the class, as long as the class is referenced by
the classloader, the object won't be collected.
And for entry level, I don't think they want to go down to discussion about
classloaders.

今天被问到了一个小的面试题如下,请大家帮忙讨论一下:
Java中,如何保证一个 singleton的实例不会被 垃圾回收?
J***e
发帖数: 50
43
来自主题: JobHunting版 - 请问一道special singleton class的题
Write a special singleton class, the class has one integer field,
make sure only one instance of this class will be instantiated for
the same value of the integer field.
以下是我写的, 但是有个问题,这样instance不是static, getInstance()因为用到
instance也不能是static,可以吗?这样解对吗?另外,当singleton object destruct的时候,应该把 value从hashmap里删除。怎么实现这个呢?用finalize()?
import java.util.HashMap;
public class SingletonInteger {
private Integer value;
private SingletonInteger instance;
private static HashMap阅读全帖
c********t
发帖数: 5706
44
我这里也有个基础问题。java里 为了防止用new create singleton class instance,
需要把 construct class scope设为private, 可是这样就不能继承了啊?
如何既能可以被继承,又可以保持singleton性质?
h*********o
发帖数: 62
45
quite hard to sync the singleton intances in a cluster if you have to. One
solution is to code a mediator on top of the cluster.
Actually singleton can also be a problem when you deploy your app as ear to
an application server in java.
g*****g
发帖数: 34805
46
I believe when you declare
private static final Singleton INSTANCE = new Singleton();
the instance is created when you load the class, not when you
call getInstance, so it's not lazy initialization and it should
be thread safe.
m******t
发帖数: 2416
47
I don't get your last paragraph - what makes you think the jvm
_must_ be doing double check locking?
As for Singleton, I really think that it is an outdated pattern.
With Dependency Injection, you almost never ever need
to use Singleton.

class,
r*****l
发帖数: 2859
48
来自主题: Java版 - Singleton
I agree that the chance is quite small. However, bad thing may happen when
there is just one classloader.
"instance_ = new Singleton()"
may be executed in this way:
1, allocate a piece of memory and give the reference to instance_.
2, initialize Singleton object.
It's possible that after 1, and before 2, another thread comes in and get a
non null instance_ and use it.
F****n
发帖数: 3271
49
来自主题: Java版 - Singleton
What's the difference between #1 and #2 since it is a Singleton class and it
will not be initialized until being loaded by a ClassLoader?
To make the point clear, you should use a user class rather than a dedicated
Singleton Class.
r*****l
发帖数: 2859
50
来自主题: Java版 - Singleton
Once the class is loaded, the static variables are loaded and initialized.
They live while the class lives. Therefore, the references they hold live
while the class lives. Singleton instance is one of the references.
The single instance can only be GCed if there is no strong reference to it,
i.e. when the ClassLoader that loaded the singleton is GCed.
1 2 3 4 5 6 7 8 9 10 下页 末页 (共10页)