目前,我使用抽象工厂来允许指定自定义类名来生成请求对象。我这样做的原因是让我可以在不更改代码的情况下轻松扩展核心功能。不过,最近,我对这种方法的有效性有些怀疑。所以我的问题是:
允许工厂实例化与预期接口匹配的任何提交的类名是工厂概念的混蛋吗?我会更好地避免这种情况吗?
更新
这里的逻辑是这样的:一方面,现实生活中的汽车工厂(例如)如果没有配备制造这种汽车的机器,就无法制造汽车。另一方面,下面的代码就像给同一家汽车工厂提供蓝图来制造它原本不打算制造的定制汽车。
另一种方法是传入一个配置对象,指定可以与工厂一起使用的自定义类名,并限制工厂仅在它与配置指定的自定义类名特别匹配时才生成自定义类。有什么想法吗?
以及相关代码...
<?php
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');