Going one step ahead in the example why both the product subclasses (Battery & Disc ) gets instantiated .
public class Disc extends Product {
private int capacity;
public Disc() {
super();
}
public Disc(
String name, double price) {
super(name, price);
System.out.println("INVOKING DISC SUBCLASS");
}
public class Battery extends Product{
private boolean rechargeable;
public Battery() {
super();
}
public Battery(String name, double price) {
super(name, price);
System.out.println("INVOKING BATTERY SUBCLASS");
}
}
public class ProductCreator {
public static Product createProduct(String productId) {
if ("aaa".equals(productId)) {
return new Battery("AAA", 2.5);
} else if ("cdrw".equals(productId)) {
return new Disc("CD-RW", 1.5);
}
throw new IllegalArgumentException("Unknown product");
}
}
and in the main.java
public class Main {
public static void main(String[] args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
Product aaa = (Product) context.getBean("aaa");
}
applicationContext.xml
<bean id="aaa" class="com.ProductCreatorFactory.ProductCreator"
factory-method="createProduct">
<constructor-arg value="aaa" />
</bean>
<bean id="cdrw" class="com.ProductCreatorFactory.ProductCreator"
factory-method="createProduct">
<constructor-arg value="cdrw" />
</bean>
OUTPUT :--
INVOKING BATTERY SUBCLASS
INVOKING DISC SUBCLASS
how both of them get instantiated .