class MyConcreteFactory
{
public static function create($model, $typeId)
{
if ($typeId == 'customer') {
return new CustomerWrapper($model);
}
if ($typeId == 'order') {
return new OrderWrapper($model);
}
if ($typeId == 'product') {
return new ProductWrapper($model);
}
}
}
我怎样才能改善这一点? 主要缺陷是,每次引入或更改新的实体类型时,都需要更改管理 typeId 检查逻辑。
这取决于您使用的语言提供的功能。 一种方法是从配置文件中读取字符串以键入映射。
class MyConcreteFactory
{
private Map(string, constructor) KnownTypes = ReadFromConfig();
public static function create($model, $typeId)
{
var constructor = KnownTypes($typeId);
var result = constructor($model);
return result;
}
}
在java
中,您可以在Reflection API的帮助下改进模式。
public class Example {
public static Object create(Class c) {
try {
//Creating a new instance with the default constructor of that Class
return c.newInstance();
} catch (Exception e) {e.printStackTrace();}
return null;
}
public static void main(String[] args) {
//For example: Instantiating a HashMap
HashMap hashMap = (HashMap) create(HashMap.class);
}
}
有用的链接
很大
程度上取决于上下文。如果你只想要一个包装器,只需传递一个扩展可包装接口的对象并包装它。
public interface Wrappable { public Wrapped wrap() }
public class Factory {
static WrappedObj create(Wrappable model) {
return model.wrap();
}
}