Factory Pattern using java for input parameter class
I have Method which return respected Factory base on behavior it should return respected Factory object. How should I implement this using java?
public Object getCurre开发者_StackOverflow社区ntBehaviour(Class behavior) {
//e.g behavior type is entity it should return entity factory
//if behavior type is VO it should return VO factory
}
class EntiryFactory{
}
class VoFactory{
}
I would suggest you create 2 bases classes, 1 for entity, 1 for VO.
Example:
public abstract class Entity implements Serializable {
}
public abstract class AbstractVO {
}
Then, use a Abstract Factory pattern for each object's Factory
public AbstractFactory {
private AbstractFactory() {}
public abstract Factory getFactory(Class clazz) {
if (Entity.class.isAssignableFrom(clazz)) {
return new EntityFactory();
}
if (AbstractVO.class.isAssignableFrom(clazz)) {
return new VOFactory();
}
return null;
}
}
I am using a Class.isAssignableFrom()
method to say that subclassed classes is assignable from the parent class (which it does, if you understand what I'm trying to say). That's the trick here.
For this, I would make a Factory for each object
public abstract Factory<T> {
public abstract T createObject();
}
public class EntityFactory extends Factory<Entity> {
public Entity createObject(Class entityClass) {
try {
return entityClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class VOFactory extends Factory<AbstractVO> {
public AbstractVO createObject(Class voClass) {
try {
return voClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Finally, getting the object
Entity entity = (Entity)AbstractFactory.getFactory(Entity.class).createObject();
If I understood your question correctly, I believe you are essentially asking how to return the appropriate instance from getCurrentBehaviour(Class behaviour)
Since the argument is a Class
object, you can use Class.isAssignableFrom(Class c)
to check if the class or interface represented by this Class
object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class
parameter.
Here goes:
public Object getCurrentBehaviour(Class behavior) {
if(behavior.isAssignableFrom(EntiryFactory.class) {
// create an instance of EntiryFactory
}
else if(behavior.isAssignableFrom(VoFactory.class) {
// create an instance of VoFactory
}
return created_instance;
}
精彩评论