工厂方法模式
public abstract class Product {
public void method1(){
}
public abstract void method2();
}
public class ConcreteProduct1 extends Product {
public void method2(){
System.out.println("product1");
}
}
public class ConcreteProduct2 extends Product{
public void method2(){
System.out.println("product2");
}
}
public abstract class Creator {
public abstract <T extends Product> T createProduct(Class<T> c);
}
public class ConcreteCreator extends Creator {
@SuppressWarnings("unchecked")
public <T extends Product> T createProduct(Class<T> c) {
Product product = null;
try {
product = (Product) Class.forName(c.getName()).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return (T) product;
}
}
public class Client {
public static void main(String[] args){
Creator creator = new ConcreteCreator();
Product product1 = creator.createProduct(ConcreteProduct1.class);
Product product2 = creator.createProduct(ConcreteProduct2.class);
product1.method2();
product2.method2();
}
}