Factory模式

来源:互联网 发布:网页美工基本知识 编辑:程序博客网 时间:2024/06/03 17:36

属于Creational Design Patterns。用于创建concrete class。

Intent

  • creates objects without exposing the instantiation logic to the client.
  • refers to the newly created object through a common interface The implementation is really simple

Implementation

  • The client needs a product, but instead of creating it directly using the new operator, it asks the factory object (通常就是个工厂类)for a new product, providing the information about the type of object it needs.
  • The factory instantiates a new concrete product and then returns to the client the newly created product(casted to abstract product class).
  • The client uses the products as abstract products without being aware about their concrete implementation.

需要注意的是,客户端既不知道,也不关心被实例化的类是什么,而只是得到了一个抽象类。

the factory class is usually used as a singleton。

 

public class ProductFactory{
public Product createProduct(String ProductID){
if (id==ID1)
return new OneProduct();
if (id==ID2) return
return new AnotherProduct();
... // so on for the other Ids

        return null; //if the id doesn't have any of the expected values
    }
    ...
}这个是最简单的noob factory。Factory模式

 

为了解决每次新增一个新product的时候就需要修改工厂类的问题,菜鸟工厂需要做一下改变:

class ProductFactory
{
private HashMap m_RegisteredProducts = new HashMap();

public void registerProduct (String productID, Class productClass)
{
m_RegisteredProducts.put(productID, productClass);
}

public Product createProduct(String productID)
{
Class productClass = (Class)m_RegisteredProducts.get(productID);
Constructor productConstructor = cClass.getDeclaredConstructor(new Class[] { String.class });
return (Product)productConstructor.newInstance(new Object[] { });
}
}

在工厂类中使用map来存储productID和product class type(这样可以想放多少就放多少)。然后在代码中的任意地方都可以注册新的product。问题解决~

然而新的问题又出现了:

我们必须在调用工厂前完成所有product的注册。如果注册product的代码在调用工厂之后,则会找不到想实例化的类。

于是对反射的应用又诞生了~~达到的效果是the static block in each class will be executed when each class is loaded

不过我觉得就用noob factory挺好的。后面的方法虽然灵活,但是逻辑过于分散。把class creation都放在factory class里改起来简单。

如果不想使用反射,我们需要的是让每个类自己解决注册的问题,而不是在工厂里注册:

 

abstract class Product
{
public abstract Product createProduct();
...
}

class OneProduct extends Product
{
...
static
{
ProductFactory.instance().registerProduct("ID1", new OneProduct());
}
public OneProduct createProduct()
{
return new OneProduct();
}
...
}

class ProductFactory
{
public void registerProduct(String productID, Product p)    {
m_RegisteredProducts.put(productID, p);
}

public Product createProduct(String productID){
((Product)m_RegisteredProducts.get(productID)).createProduct();

//所以不是工厂创建的concrete class

//而是调用class中的createProduct方法。
 }
}

A more advanced solution - Factory design pattern with abstractions(Factory Method)

next section~~~!!

原创粉丝点击