引言 语言的进步,可以简化设计模式的实现.
Singleton模式
类型:创建型
意义:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
1.D的实现
一个类的实现
[code]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;
}
[/code]
实现后每次都要复制粘贴,很累,用模版类,更方便:
[code]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;
}[/code]
2.使用例子
[code]
class Option:Singleton!(Option)
{
char[] foo(){ return "Hello!";}
}
int main()
{
writefln(Option().foo);
return 0;
}
[/code]
Singleton模式
类型:创建型
意义:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
1.D的实现
一个类的实现
[code]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;
}
[/code]
实现后每次都要复制粘贴,很累,用模版类,更方便:
[code]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;
}[/code]
2.使用例子
[code]
class Option:Singleton!(Option)
{
char[] foo(){ return "Hello!";}
}
int main()
{
writefln(Option().foo);
return 0;
}
[/code]