[疑难] D可以实现单体模式吗?谁能给个例子?

myyxm 2007-07-11
如上题
DavidL 2007-07-11
可以,singleton的东东自己到NewsGroup里面搜一搜可以找到。看到过几次,不过还没真正用过。
myyxm 2007-07-11
谢谢!我在dotmars的源代码中找到了,贴出来

/**
Singleton Holder Template

Authors:
	Wei Li(oldrev@gmail.com)

License:
	BSD

Copyright:
	Copyright (C) 2007 Wei Li. All rights reserved.
*/

module dotmars.base.singletion;

//TODO: 线程 policy? 


/**
  * SingletonHolder is a implemention of singleton pattern
  */
final static class SingletonHolder(T)
{
	public alias SingletonHolder!(T) SelfType;
   	private static T m_instance;

   	private static this()
   	{
        static assert(is(T == class) || is(T == struct) || is(T == union), 
                "SingletonHolder: struct, union and class only");

		static if(is(T == class))
   			m_instance = new T();
	}

    public static T instance()
    {
		static if(is(T == class))
            assert(m_instance !is null);
           
        return m_instance;
    }

    public static T opCall()
    {
        return instance;
    }

	public static T opCast()
	{
		return instance;
	}
}

xgene 2007-07-11
和上面差不多;
class Singleton(T) {  
 
static class SingletonHolder(T)
{  
static T instance;
static this()
{
static assert(is(T == class) ,__FILE__~":Singleton(T) used for class only");
instance = new T();
}

}  
 
public static T instance() {  
return SingletonHolder!(T).instance;  
}  
public static T opCall()
{
return instance;
}

public static T opCast()
{
return instance;
}
}
oldrev 2007-07-13
貌似 opCast 有点多余
oldrev 2007-07-13
这是例子:

class Foo //需要成为Singleton的类
{
    int x;
    int bar() { return x; }
}

alias SingletonHolder!(Foo) Foobar;

int v = Foobar.instance.bar;
v = Foobar().bar;
Global site tag (gtag.js) - Google Analytics