I was studying about Factory Pattern
in this link. After writing a normal factory, the author goes on to design a factory where we don't have to modify the factory's code to add new concrete implementations. (Let's say there's a Product
interface and factory provides it's implementations).
To achieve this, the author says:
We add a new abstract method in the product abstract class. Each concrete class will implement this method to create a new object of the same type as itself.
And this code snippet follows:
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();
}
}
I've a doubt here. We are already registering an instance of OneProduct to the factory. Then at runtime, we are calling createProduct()
method which again creates a new instance of Oneproduct
.
Is this the correct way of doing this? We have to create two instances of OneProduct
here which I feel is wrong.
Aucun commentaire:
Enregistrer un commentaire