Depend upon abstractions. Do not depend on concrete classes.
…for some definition of “should”
With past patterns, we have been abstracting and encapsulating behavior, dependencies, etc. and making them runtime properties, increasing extensibility, etc.
To eliminate coupling introduced by the new operator, we will now abstract and encapsulate object instantiation using factories.
Defines an interface for creating an object, but let’s subclasses decide which class to instantiate. The Factory Method Pattern lets a class defer instantiation to a subclass.
AKA: Virtual Constructor
public interface Product{
// ...
}
public class Car implements Product{
// ...
}
public class Boat implements Product{
// ...
}
public abstract class Producer{
public Product produce(){
Product p = createProduct();
// do stuff with product
return p;
}
protected abstract Product createProduct();
}
Note that the Producer only has dependencies on the Product interface, just like the Car and Boat classes. This class can now be closed for modification since we have inverted our dependencies.
public CarProducer extends Producer{
protected Product createProduct(){
return new Car();
}
}
public BoatProducer extends Producer{
public Product createProduct(){
return new Boat();
}
}
A common goal of good design is to simply take the bad stuff you can’t eliminate from your code entirely, and isolate it in the smallest number of locations possible. This applies to:
If the only thing the subclass does is instantiate an object, then maybe we’re just making our lives more difficuly for no reason.
If you are already subclassing, though, then it’s fine.
Provides an interface for creating families of related or dependent objects without specifying their concrete classes.
If we need to add a new type of product, it can be difficult, because all product families must be updated.