From GOF book:
Class patterns deal with relationships between classes and their subclasses. These relationships are established through inheritance, so they are static-fixed at compile-time. Object patterns deal with object relationships, which can be changed at run-time and are more dynamic. Almost all patterns use inheritance to some extent. So the only patterns labeled "class patterns" are those that focus on class relationships.
Why is factory method a class pattern, and abstract factory an object pattern, given that they seem to be very similar patterns?
Thanks.
The GOF book says
Intent
Define an interface for creating an object, but let subclasses decide which class to instantiate.
What does this mean? Let's take a look at the example that the book shows.
In the example a framework defines the Application
interface to let others implement it. This means that I can implement e.g. a MyApplication
or MyOtherApplication
like this:
public class MyApplication extends Application {
protected Document createDocument() {
return new MyDocument();
}
}
public class MyOtherApplication extends Application {
protected Document createDocument() {
return new MyOtherDocument();
}
}
When the framework starts it might choose one of these implementations depending on what it finds on the classpath.
But it means that after the framework has instantiated either MyApplication
or MyOtherApplication
the way a document is created is fix. The way a document is created can not be changed anymore at runtime for the Application
instance. There is no setter or anything else that you can use to change the way the Document
is created. Thus it is also called a virtual constructor and thus it is a class pattern.
In contrast to the factory method an abstract factory can be changed at runtime and thus the way the objects it creates. That's why they say it is an object pattern.
A abstract factory is also responsible for creating
... families of related or dependent objects ...
This is also a difference to the factory method aka. virtual constructor.