1) 工廠類角色:這是本模式的核心,含有一定的業務邏輯和判斷邏輯。在java中它往往由一個具體類實現。
2) 抽象產品角色:它一般是具體產品繼承的父類或者實現的接口。在java中由接口或者抽象類來實現。
3) 具體產品角色:工廠類所創建的對象就是此角色的實例。在java中由一個具體類實現。
public static Product createProduct(String type){
if(type.equals("A")){
return new ConcreteProductA();
}else if(type.equals("B")){
return new ConcreteProductB();
}else{
return null ;
}
}
3) 抽象產品角色:它是具體產品繼承的父類或者是實現的接口。在java中一般有抽象類或者接口來實現。
abstract class Product{
}
abstract class Factory{
public Product createProduct(){
return null;
}
}
class ConcreteProduct extends Product{
}
class ConcreteFactory extends Factory{
public Product createProduct(){
return new ConcreteProduct();
}
}
class Class<T> implements java.io.Serializable,... {
abstract class Product{
}
abstract class Factory{
public Product createProduct(){
return null;
}
}
class ConcreteProduct extends Product{
}
class ConcreteFactory extends Factory{
public Product createProduct(){
return new ConcreteProduct();
}
}
// 通過靜態工廠方法 static Class<?> forName(String className),獲取到具體Class工廠對象。
@CallerSensitive
public static Class<?> forName(String className)
throws ClassNotFoundException {
return forName0(className, true,
ClassLoader.getClassLoader(Reflection.getCallerClass()));
}
//然後通過具體Class工廠對象newInstance(),生產該工廠中的具體實例產品對象。
@CallerSensitive
public T newInstance()
throws InstantiationException, IllegalAccessException
{
if (System.getSecurityManager() != null) {
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);
}
// NOTE: the following code may not be strictly correct under
// the current Java memory model.
// Constructor lookup
if (cachedConstructor == null) {
if (this == Class.class) {
throw new IllegalAccessException(
"Can not call newInstance() on the Class for java.lang.Class"
);
}
try {
Class<?>[] empty = {};
final Constructor<T> c = getConstructor0(empty, Member.DECLARED);
// Disable accessibility checks on the constructor
// since we have to do the security check here anyway
// (the stack depth is wrong for the Constructor's
// security check to work)
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {
public Void run() {
c.setAccessible(true);
return null;
}
});
cachedConstructor = c;
} catch (NoSuchMethodException e) {
throw new InstantiationException(getName());
}
}
Constructor<T> tmpConstructor = cachedConstructor;
// Security check (same as in java.lang.reflect.Constructor)
int modifiers = tmpConstructor.getModifiers();
if (!Reflection.quickCheckMemberAccess(this, modifiers)) {
Class<?> caller = Reflection.getCallerClass();
if (newInstanceCallerCache != caller) {
Reflection.ensureMemberAccess(caller, this, null, modifiers);
newInstanceCallerCache = caller;
}
}
// Run constructor
try {
return tmpConstructor.newInstance((Object[])null);
} catch (InvocationTargetException e) {
Unsafe.getUnsafe().throwException(e.getTargetException());
// Not reached
return null;
}
}
....
....
}