D语言动态创建对象-D最新功能
我认为这是D提供的又一个重量级的功能.闲言少叙,代码说话!
保存为cre.d,使用dmd cre.d编译.
Java代码
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;
}
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;
}
根据这个功能,结合动态链接库,可以提供简单插件的功能了!!!
实现了IOC,针对抽象进行依赖.
更多信息请登陆http://61.191.27.74:802/ 最后,欢迎加入http://61.191.27.74:802/的会员
安徽新华电脑学校专业职业规划师为你提供更多帮助【在线咨询】