我认为这是D提供的又一个重量级的功能.闲言少叙,代码说话!
保存为cre.d,使用dmd cre.d编译.
[code]module cre;
import std.stdio;
interface IPrinter
{
void print();
void init(char[] a);
}
class foo :IPrinter
{
void print()
{
writefln("foo OK "~fb);
}
void init(char[] a)
{
fb = " Hollo "~a;
}
char[] fb;
}
class fbb :IPrinter
{
void print()
{
writefln("fbb:OK! "~fb);
}
void init(char[] a)
{
fb = "Thank you "~a;
}
char[] fb;
}
//IOC Factory.
class Factory(T)
{
static T create(char[] Name)
{
T instance =cast(T)Object.factory(Name);
assert(instance);
return instance;
}
}
int main()
{
writefln("Factory Test!");
alias Factory!(IPrinter) PT;
IPrinter a = PT.create("cre.foo");
a.init("Walter!");
a.print();
IPrinter b = PT.create("cre.fbb");
b.init("Walter!");
b.print();
return 1;
}
[/code]
根据这个功能,结合动态链接库,可以提供简单插件的功能了!!!
实现了IOC,针对抽象进行依赖.
昨天看到,晚上想到了,早晨实现了,现在贴上, 真不错.
保存为cre.d,使用dmd cre.d编译.
[code]module cre;
import std.stdio;
interface IPrinter
{
void print();
void init(char[] a);
}
class foo :IPrinter
{
void print()
{
writefln("foo OK "~fb);
}
void init(char[] a)
{
fb = " Hollo "~a;
}
char[] fb;
}
class fbb :IPrinter
{
void print()
{
writefln("fbb:OK! "~fb);
}
void init(char[] a)
{
fb = "Thank you "~a;
}
char[] fb;
}
//IOC Factory.
class Factory(T)
{
static T create(char[] Name)
{
T instance =cast(T)Object.factory(Name);
assert(instance);
return instance;
}
}
int main()
{
writefln("Factory Test!");
alias Factory!(IPrinter) PT;
IPrinter a = PT.create("cre.foo");
a.init("Walter!");
a.print();
IPrinter b = PT.create("cre.fbb");
b.init("Walter!");
b.print();
return 1;
}
[/code]
根据这个功能,结合动态链接库,可以提供简单插件的功能了!!!
实现了IOC,针对抽象进行依赖.
昨天看到,晚上想到了,早晨实现了,现在贴上, 真不错.