VDV*_*eon 6 oop d factory-pattern
我注意到D中的函数Object.factory(char [] className)但它不能像我希望的那样工作; 这是行不通的 ;)
一个例子:
import std.stdio;
class TestClass
{
override string toString()
{
return typeof(this).stringof; // TestClass
}
};
void main(string[] args)
{
auto i = Object.factory("TestClass");
if (i is null)
{
writeln("Class not found");
}
else
{
writeln("Class string: " ~ i);
}
}
Run Code Online (Sandbox Code Playgroud)
我认为这应该导致消息:"类字符串:TestClass",但它说"找不到类".
有谁知道为什么会这样,我怎么能解决它?
或者我是否需要建立自己的班级工厂.例如,通过使用Object[string] classes;
带有类实例的静态数组创建一个类.当我想要一个新实例时,我这样做:
auto i = (className in classes);
if (i is null)
{
return null;
}
return i.classinfo.create();
Run Code Online (Sandbox Code Playgroud)
编辑:
我现在就像这样使用它(例如,这是针对Web HMVC模式):
class Page : Controller
{
static this()
{
register(Page.classinfo);
}
protected void registerActions()
{
registerAction("index", &index);
}
public void index()
{
request.response = "Page: " ~ request.params.get("pageID", "0") ~ " in format: " ~ request.params.get("format", "html");
}
};
void main(string[] args)
{
Route.add(
r"page/(\d+)\.(html|json)",
[
1: "pageID",
2: "format"
],
[
"controller": "page" // tell route to use page as controller class
]
);
Route.add(
r"(\S+)/(\S+)",
[
1: "controller", // get controller class from uri
2: "action" // get controller action from uri
]
);
auto request = Request.factory("/page/43.json").execute();
// Headers and response can be accessed like this
// Can be used in http response
uint code = request.getCode();
const(string[string]) headers = request.getHeaders();
string response = request.response;
}
Run Code Online (Sandbox Code Playgroud)
在C++中很难做到这种东西;)
这是一个有效的:
module irc2;
import std.stdio;
class TestClass
{
override string toString()
{
return typeof(this).stringof; // TestClass
}
};
void main(string[] args)
{
auto i = Object.factory("irc2.TestClass");
if (i is null)
{
writeln("Class not found");
}
else
{
writeln("Class string: " ~ i.toString);
}
}
Run Code Online (Sandbox Code Playgroud)
有几点需要注意:
writefln("Class string: %s", i)
.