目前,我使用抽象工厂来允许指定自定义类名来生成请求对象。我这样做的理由是让我可以在不改变代码的情况下轻松扩展核心功能。不过,最近我对这种方法的功效有些怀疑。所以我的问题是这样的:
Is allowing the factory to instantiate any submitted class name that
matches the expected interface a bastardization of the factory concept?
Would I be better served to avoid this?
UPDATE
这里的逻辑是这样的:一方面,一个真实的汽车制造厂(例如)如果没有配备制造这种汽车的机器,就不能制造汽车。另一方面,下面的代码就像给同一个汽车制造厂制作蓝图,以制造它最初不打算制造的定制汽车。
另一种方法是传入一个配置对象,指定一个可能与工厂一起使用的自定义类名称,并限制工厂生成一个自定义类,只要它特别匹配配置指定的自定义类名称。有什么想法吗?
和相关的代码...
interface AbstractRequestFactory
{
public function buildRequest($type);
}
class RequestFactory implements AbstractRequestFactory
{
public function buildRequest($type='http')
{
if ($type == 'http') {
return new HttpRequest();
} elseif ($type == 'cli') {
return new CliRequest();
} elseif ($custom = $this->makeCustom($type)){
return $custom;
} else {
throw new Exception("Invalid request type: $type");
}
}
protected function makeCustom($type)
{
if (class_exists($type, FALSE)) {
$custom = new $type;
return $custom instanceof RequestInterface ? $custom : FALSE;
} else {
return FALSE;
}
}
}
// so using the factory to create a custom request would look like this:
class SpecialRequest implements RequestInterface {}
$factory = new RequestFactory();
$request = $factory->buildRequest('\SpecialRequest');