I've read the following article in this link.
Please refer to section Class Registration - avoiding reflection only.
In this example I cannot get the meaning of the following code line:
static
{
ProductFactory.instance().registerProduct("ID1", new OneProduct());
}
The issues that are not clear to me:
1.Where is the method instance() defined?
2.Is instance method should be static, if so how its implementation will look a like?
(return this
isn't possible through static method)
*Please stick to the given example unless it is wrong, I'm trying to focus on one factory "recipe".
I am trying to answer your questions below:
1.Where is the method instance() defined?
The method is defined in the class ProductFactory
, which is obvious.
2.Is instance method should be static, if so how its implementation will look a like?
Yes, it should be static
. Please have a look at the definition of class ProductFactory
and instance()
method below:
public class ProductFactory extends Factory
{
private static ProductFactory _instance;
private HashMap m_RegisteredProducts = new HashMap();
public static synchronized 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){
((Product)m_RegisteredProducts.get(productID)).createProduct();
}
}