我从http://www.oodesign.com/factory-pattern.html借用了以下大部分代码(从 //start 开始)
我的问题是 ProductOne 类中的注册不会发生,除非我在客户端代码中调用 Class.forName("ProductOne") 。
是否有可能使 ProductOne 自包含?换句话说,所以我的客户端代码只有
public class Main {
public static void main(String[] args) {
Product p = ProductFactory.instance().createProduct("ID1");
}
}
不抛出 NullPointerException?非常感谢!
//start
import java.util.HashMap;
public class ProductFactory {
private static ProductFactory instance;
private HashMap m_RegisteredProducts = new HashMap();
private ProductFactory()
{
System.out.println("ProductFactory(): Initializing Instance");
}
public static ProductFactory instance()
{
if (instance==null)
instance = new ProductFactory();
return instance;
}
public void registerProduct (String productID, Product p)
{
m_RegisteredProducts.put(productID, p);
}
public Product createProduct(String productID)
{
return ((Product)m_RegisteredProducts.get(productID)).createProduct();
}
}
public abstract class Product {
public abstract Product createProduct();
}
public class ProductOne extends Product {
static {
ProductFactory.instance().registerProduct("ID1", new ProductOne());
}
public ProductOne()
{
System.out.println("Initializing ProductOne");
}
@Override
public Product createProduct() {
return new ProductOne();
}
}
public class Main {
static {
try
{
Class.forName("ProductOne");
}
catch (ClassNotFoundException any)
{
any.printStackTrace();
}
}
public static void main(String[] args) {
Product p = ProductFactory.instance().createProduct("ID1");
}
}