Explain the main differences between the 'Factory Method' and 'Abstract Factory' patterns.
sobes.tech AI
Answer from AI
The Factory Method pattern defines an interface for creating an object but allows subclasses to decide which class to instantiate. In other words, the creation of a specific object is delegated to subclasses. It is typically used when there is one product and several options for its implementation.
Abstract Factory provides an interface for creating families of related or dependent objects without specifying their concrete classes. It is a higher-level pattern that combines multiple factory methods to create different but related objects.
Main differences:
- Focus: Factory Method creates a single product, Abstract Factory creates a family of products.
- Structure: Factory Method is usually implemented through inheritance and overriding the creation method, Abstract Factory through composition and a set of interfaces.
- Usage: Factory Method is suitable when creating objects of one type with variations, Abstract Factory when creating related objects of different types that need to work together.
Example in Dart (Flutter) for Factory Method:
abstract class Button {
void render();
}
class AndroidButton implements Button {
@override
void render() => print('Android Button');
}
class IOSButton implements Button {
@override
void render() => print('iOS Button');
}
abstract class Dialog {
Button createButton();
void render() {
var button = createButton();
button.render();
}
}
class AndroidDialog extends Dialog {
@override
Button createButton() => AndroidButton();
}
class IOSDialog extends Dialog {
@override
Button createButton() => IOSButton();
}
Here, Dialog is the factory method that creates different buttons depending on the platform.
The Abstract Factory would include creating multiple related products, such as buttons and checkboxes, that should be compatible with each other.