Java 工厂方法模式
程序员文章站
2024-01-05 23:39:34
...
定义:定义一个创建对象的接口,让子类决定实例化哪一个类。
抽象产品类:
public abstract class Product {
public abstract void detail();
}
具体产品类:
public class Car extends Product {
@Override
public void detail() {
System.out.println("汽车");
}
}
public class Plane extends Product {
@Override
public void detail() {
System.out.println("飞机");
}
}
抽象工厂类:
public abstract class Creator {
public abstract <T extends Product> T createProduct(Class<T> clazz);
}
具体工厂类:
public class CreatorImpl extends Creator {
@Override
public <T extends Product> T createProduct(Class<T> clazz) {
Product product = null;
try {
product = (Product) Class.forName(clazz.getName()).newInstance();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return (T) product;
}
}
实例:
public class Client {
public static void main(String[] args) {
Creator creator = new CreatorImpl();
Product product = creator.createProduct(Car.class);
product.detail();
product = creator.createProduct(Plane.class);
product.detail();
}
}
简单工厂模式:(去抽象类、静态方法)
public class SimpleFactory {
public static <T extends Product> T createProduct(Class<T> clazz) {
Product product = null;
try {
product = (Product) Class.forName(clazz.getName()).newInstance();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return (T) product;
}
}