Hello again,
During development a project, I needed a solution and would like to share it with you:
Challenge:
1. I need a abstract factory class.
2. The each classes which I am going to call have a constructor parameter. While I call a class instance from factory class, I needed to set the constructor parameter as well.
3. For this, I prefer to use ENUM as the best practice of factory pattern of Java.
The sample project which satisfy these 3 necessities below. The way of setting parameter during call of newInstance(), we use getDeclaredConstructor().newInstance();
During development a project, I needed a solution and would like to share it with you:
Challenge:
1. I need a abstract factory class.
2. The each classes which I am going to call have a constructor parameter. While I call a class instance from factory class, I needed to set the constructor parameter as well.
3. For this, I prefer to use ENUM as the best practice of factory pattern of Java.
The sample project which satisfy these 3 necessities below. The way of setting parameter during call of newInstance(), we use getDeclaredConstructor().newInstance();
Have fun!
public class Main {
public static void main(String[] args)
{
MyGenericClass mgc = MyClassFactory.instanceOf(MyClassFactory.MYCLASS, "This is My
Class");
MyGenericClass mgc2 = MyClassFactory.instanceOf(MyClassFactory.MYSECONDCLASS, "This is My
Second Class");
}
}
This is My Class
This is My Second Class
public abstract class MyGenericClass {
public
MyGenericClass(String s)
{
System.out.println(s);
}
}
public class MyClass extends MyGenericClass {
public MyClass(String s) {
super(s);
}
}
public class MySecondClass extends MyGenericClass{
public MySecondClass(String
s) {
super(s);
}
}
public enum MyClassFactory {
MYCLASS(MyClass.class), MYSECONDCLASS(MySecondClass.class);
private static final
Map<MyClassFactory, Class<MyGenericClass>> lookup = new
HashMap<MyClassFactory, Class<MyGenericClass>>();
static {
for (MyClassFactory
myClass : EnumSet.allOf(MyClassFactory.class))
lookup.put(myClass, (Class<MyGenericClass>)
myClass.getClazz());
}
private Class<? extends MyGenericClass> clazz;
MyClassFactory(Class<? extends MyGenericClass>
clazz) {
this.clazz = clazz;
}
private Class<? extends MyGenericClass>
getClazz() {
return clazz;
}
public static <T extends MyGenericClass> T
instanceOf(MyClassFactory clazz, String message) {
if (lookup.containsKey(clazz))
{
try {
return (T) lookup.get(clazz).getDeclaredConstructor(String.class).newInstance(message);
}
catch
(InstantiationException e) {
e.printStackTrace();
}
catch
(IllegalAccessException e) {
e.printStackTrace();
}
catch (IllegalArgumentException
e) {
return null;
}
catch (SecurityException
e) {
e.printStackTrace();
}
catch
(InvocationTargetException e) {
e.printStackTrace();
}
catch
(NoSuchMethodException e) {
e.printStackTrace();
}
}
return null;
}
}
Hiç yorum yok:
Yorum Gönder