dimanche 17 juillet 2016

Best factory implementation

So because I'm currently reading into design patters I have a "newbie" and at least for me interesting question to ask.

What Factory implementation is the best? I've seen factories where the create method is hardcoded and if a new subtype is added I'll need to edit the method. For example:

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
    }
    ...
}

This seems to be the implementation that takes the lowest amount of resources. But furthemore I've seen implementations that use reflection:

class ProductFactory
{
    private HashMap<String, Class> 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[] { });
    }
}

Which seems to be the slowest one because it is using reflection to work. And the last implementation seems to take the most RAM because it has an extra instance of a specific class stored.

class ProductFactory
{
    private HashMap<String, Product> m_RegisteredProducts = new HashMap<>();

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

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

Both the second last and last implementation allow to register new products without modifying the factory class in for example a static block in the to be registered product extending/implementing class. Is this better? And if so, which of those two implementation is the better one? Or is the hard coded implementation better because it seems to require less resources.

Aucun commentaire:

Enregistrer un commentaire