2007-03-07

D语言设计模式 Singleton

关键字: 设计模式 D Singleton
引言 语言的进步,可以简化设计模式的实现.

Singleton模式

类型:创建型

意义:保证一个类仅有一个实例,并提供一个访问它的全局访问点。

1.D的实现

一个类的实现
class Singleton
{
public:
    static Singleton opCall()
    {
        if(_instance is null) _instance = new Singleton;
        return _instance;
    }
protected void init(){}
private:
    this() {this.init();}
    static Singleton _instance;
}

实现后每次都要复制粘贴,很累,用模版类,更方便:
class Singleton(T)
{  
  public static T opCall()
  {
    if(_instance is null) _instance = new T;
    return _instance;
  }
	
	protected void init(){}
	
  private:
    this() { this.init(); }

    static T _instance;
}


2.使用例子
class Option:Singleton!(Option)
{
   char[] foo(){ return "Hello!";}
}

int main()
{
   writefln(Option().foo);
   return 0;
}
评论
oldrev 2007-03-07
引用
3.支持多数类型!!!

经过实践证明这只是理论上的,D没有值类型的透明引用类型,这使得SingletonHolder类只能作右值。
如果要支持内置类型(比如int)的话需要修改 instance() 让其返回指针才能修改int的值,而且Singleton本来就是面向对象的概念,支持内置类型也没太大的必要,那么干脆就只支持 class 、struct、union 好了。
ideage 2007-03-07
赞一个!
引用
SingletonHolder 类避免了继承的麻烦,而且可以支持struct和内置类型


1.用法简洁,不用修改现存的类.
2.优先使用组合,尽量避免继承.
3.支持多数类型!!!
oldrev 2007-03-07
终极修正版:
final class SingletonHolder(T)
{
   	private static T m_instance;

   	private static this()
   	{
		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;
	}
}

oldrev 2007-03-07
SingletonHolder 类避免了继承的麻烦,而且可以支持struct和内置类型
oldrev 2007-03-07
引用

qiezi 14 分钟前

代码

1. alias SingletonHolder!(Foo) S;
2. S().x = 2;

D语言里面可以省去0参数方法的括号,S().x改成S.x能不能编译?我现在出差不方便测试。。。

测试结果:编译错误

楼上说的那个特性好像是0.177新添加的两个struct特性
1. struct S; S s(x) 将被编译器实现为 S s = S(x)
2. S s = x; 将实现为 S s = S(x)
也就是 struct 的 static opCall 用起来像 ctor
qiezi 2007-03-07
alias SingletonHolder!(Foo) S;   
S().x = 2;   


D语言里面可以省去0参数方法的括号,S().x改成S.x能不能编译?我现在出差不方便测试。。。
ideage 2007-03-07
写的很好!学习!!!
oldrev 2007-03-07
我写了一个不使用继承的:
final class SingletonHolder(T)
{
   	private static T m_instance;

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

    public static T instance()
    {
        assert(m_instance);
        return m_instance;
    }

    public static T opCall()
    {
        return instance;
    }

	public static T opCast()
	{
		return instance;
	}

    private ~this()
    {
    }
}

unittest
{
	class Foo
	{
		public int x;

	}

	alias SingletonHolder!(Foo) S;
	S().x = 2;
	(cast(Foo)S).x = 2;
}
发表评论

您还没有登录,请登录后发表评论

ideage
搜索本博客
最近加入圈子
存档
最新评论