基类:
import java.util.ArrayList;
import java.util.HashMap;
public class Person {
public String name;
public void say(String something) {
}
public interface Factory {
public Person create();
public String[] getSupportedExtensions();
}
static Factory[] sSubclassFactories = new Factory[] {
Student.getFactory(),
Teacher.getFactory(),
};
static ArrayList<String> sSupportedExtensions = new ArrayList<String>();
static HashMap<String, Factory> sExtensionMap =
new HashMap<String, Factory>();
static {
for (Factory f : sSubclassFactories) {
for (String extension : f.getSupportedExtensions()) {
sSupportedExtensions.add(extension);
sExtensionMap.put(extension, f);
}
}
}
public static Person create(String type) {
Factory factory = sExtensionMap.get(type);
if (factory == null) {
System.out.println("return null");
return null;
}
Person person = factory.create();
return person;
}
}
继承它的类:
public class Student extends Person {
public static String name = "Student";
public void say(String something) {
System.out.println("Student Say: " + something);
}
public static Factory getFactory() {
return new Factory() {
public Person create() {
System.out.println("return student");
return new Student();
}
public String[] getSupportedExtensions() {
return new String[] { "student" };
}
};
}
}
public class Teacher extends Person{
public static String name = "Teacher";
public void say(String something) {
System.out.println("Teacher Say: " + something);
}
public static Factory getFactory() {
return new Factory() {
public Person create() {
System.out.println("return teacher");
return new Teacher();
}
public String[] getSupportedExtensions() {
return new String[] { "teacher" };
}
};
}
}
测试代码
public class Test {
private Person teacher = null;
private Person student = null;
public static void main(String arg[]) {
Test test = new Test();
test.teacher = Person.create("teacher");
test.teacher.say(test.teacher.name);
test.student = Person.create("student");
test.student.say(test.student.name);
}
}