Reputation: 35734
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);
}
}
}
How can i improve this? The main flaw is that managing the typeId checking logic will need changed every time a new entity type is introduced or changed.
Upvotes: 0
Views: 34
Reputation: 86064
It depends on the facilities provided by the language you're using. One approach is to read the string to type mapping out of a configuration file.
class MyConcreteFactory
{
private Map(string, constructor) KnownTypes = ReadFromConfig();
public static function create($model, $typeId)
{
var constructor = KnownTypes($typeId);
var result = constructor($model);
return result;
}
}
Upvotes: 2
Reputation: 7707
Depends very much on the context. If you just want a wrapper just pass an object that extends a wrappable interface and wrap it.
public interface Wrappable { public Wrapped wrap() }
public class Factory {
static WrappedObj create(Wrappable model) {
return model.wrap();
}
}
Upvotes: 0
Reputation: 382
In java you can improve your pattern with help of the 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);
}
}
Upvotes: 0