I have below example of abstract method patter.
public interface Product {
public void draw();
public void move();
}
public abstract class Creator {
public Product anOperation() {
Product product = factoryMethod();
return product;
}
public abstract Product factoryMethod();
}
public class ConcreateProduct1 implments Product {
public void draw() {
}
public void move():
}
}
public class ConcreteCreator1 extends Creator {
public Product factoryMethod() {
return new ConcreateProduct1();
}
}
public class Client {
public static void main(String arg[]) {
Creator creator = null;
creator = new ConcreteCreator1();
creator.anOperation().move();
}
}
So far I have read that flexibility to add new product is the main advantages of factory method pattern.
Can anybody explain me how we achieve flexibility which we can not achieve in below example?
public class ConcreateProduct1 {
public void draw() {
}
public void move():
}
}
public class Client {
public static void main(String arg[]) {
ConcreateProduct1 creator = new ConcreteCreator1();
creator.move();
}
}
In your example it’s mostly useless. I think the Factory pattern is never needed: you can always do the same thing in some other way, but sometimes it’s convenient to use for some reason. For example it can be used for limiting resources usage in combination with a private constructor – it’s a cache strategy.
There is also another interesting usage when coupled with reflective code. Imagine you write the Factory class without knowing any concrete implementation of the interface. The most common example is the JDBC API. From client code you access a database via a URL like
<driverId>:<params>. The Factory has aHashMap<String, Class>so it can instantiate the correct type based on<driverId>with this codeThe Factory vendor won’t need to change the implementation to add new Drivers, because they are dinamically registered and instantiated (in jdbc this happens via
Class.forName("com.example.Driver")). Note that this still seems like an unneeded complexity: why using a factory just to get an istance of a class you must know? In this case the clear advantage is flexibility: the driver name is a String which can be externalized (for example in a configuration file). This way the final user (not the developer) can switch between drivers without recompiling the application.