3 KiB
obj |
---|
concept |
Abstract Factory Pattern
Description:
The Abstract Factory Pattern is a creational design pattern that provides an interface for creating families of related or dependent objects without specifying their concrete classes. It is often used to ensure that a system is compatible with multiple families of objects, allowing you to switch between these families without changing the client code.
How it's Used:
-
Abstract Factory Interface: Define an abstract factory interface that declares a set of creation methods for creating abstract product objects. Each method corresponds to a different type of product.
-
Concrete Factories: Create concrete factory classes that implement the abstract factory interface. Each concrete factory is responsible for creating a specific family of related products.
-
Abstract Product Interface: Define an abstract product interface that declares the common methods that concrete product classes must implement. Each product family will have its own set of product interfaces.
-
Concrete Products: Create concrete product classes that implement the abstract product interfaces. These classes provide specific implementations for the products within each family.
-
Client Code: In the client code, use the abstract factory to create families of objects. Clients interact with the abstract factory and abstract product interfaces rather than directly with concrete classes.
Example:
Let's say you're building a user interface (UI) framework that can be used on both desktop and mobile platforms. You want to ensure that UI components like buttons and text fields are consistent within each platform but can be easily switched between platforms. Here's how the Abstract Factory Pattern can be applied:
-
Abstract Factory Interface: Define an
AbstractUIFactory
interface with methods likecreateButton
andcreateTextField
. -
Concrete Factories: Create two concrete factory classes:
DesktopUIFactory
andMobileUIFactory
, both implementing theAbstractUIFactory
. TheDesktopUIFactory
creates desktop-style UI components, while theMobileUIFactory
creates mobile-style UI components. -
Abstract Product Interfaces: Define abstract product interfaces like
Button
andTextField
that specify the methods these UI components should have. -
Concrete Products: Create concrete product classes like
DesktopButton
,MobileButton
,DesktopTextField
, andMobileTextField
, each implementing the corresponding abstract product interfaces. -
Client Code: In your application, use the appropriate factory (either
DesktopUIFactory
orMobileUIFactory
) to create UI components. For example:
AbstractUIFactory factory = getUIFactoryForPlatform();
Button button = factory.createButton();
TextField textField = factory.createTextField();
By using the Abstract Factory Pattern, you can switch between desktop and mobile UI components seamlessly by changing the factory you use, without modifying the client code.