目前,我使用抽象工厂来允许指定自定义类名来生成请求对象。我这样做的理由是让我可以在不改变代码的情况下轻松扩展核心功能。不过,最近我对这种方法的功效有些怀疑。所以我的问题是这样的:允许在PHP中使用抽象工厂模式实现自定义类实例化
是让工厂实例任何提交的类名 工厂概念的私生子一致预期的接口? 我会更好地避免这种情况吗?
UPDATE
这里的逻辑是这样的:一方面是,现实生活中的汽车厂(例如)无法创建一个车,如果它没有配备机械制造那种车。另一方面,下面的代码就像给同一个汽车制造厂制作蓝图,以制造它最初不打算制造的定制汽车。
另一种方法是在配置对象,指定了可以与工厂中使用的自定义类名来传递和工厂限制到产生的自定义类,只有当它的配置指定的自定义类名专门匹配。有什么想法吗?
及相关代码...
<?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');
你可以发布$ type代码片段吗? – 2012-02-10 00:33:31
@MikePurcell根据您的要求更新了代码的底部 – rdlowrey 2012-02-10 00:36:35
我会减少整个界面工厂和不同类型的“CLI”,“Http”工厂实现接口 – 2012-02-10 00:43:43