Senior
Can you tell me about the Abstract Factory pattern?
sobes.tech AI
Answer from AI
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.
The main idea is to separate the code that uses the objects from the code that creates them, allowing families of products to be changed without changing the client code.
Components of the pattern:
- Abstract Factory: interface for creating abstract products.
- Concrete Factories: implement the interface, creating concrete products.
- Abstract Products: interfaces for different types of products.
- Concrete Products: implementations of abstract products.
- Client: uses the factory to create products through abstract interfaces.
Example in Java:
// Abstract products
interface Button {
void paint();
}
interface Checkbox {
void paint();
}
// Concrete products for Windows
class WindowsButton implements Button {
public void paint() {
System.out.println("Drawing Windows button");
}
}
class WindowsCheckbox implements Checkbox {
public void paint() {
System.out.println("Drawing Windows checkbox");
}
}
// Concrete products for Mac
class MacButton implements Button {
public void paint() {
System.out.println("Drawing Mac button");
}
}
class MacCheckbox implements Checkbox {
public void paint() {
System.out.println("Drawing Mac checkbox");
}
}
// Abstract factory
interface GUIFactory {
Button createButton();
Checkbox createCheckbox();
}
// Concrete factories
class WindowsFactory implements GUIFactory {
public Button createButton() {
return new WindowsButton();
}
public Checkbox createCheckbox() {
return new WindowsCheckbox();
}
}
class MacFactory implements GUIFactory {
public Button createButton() {
return new MacButton();
}
public Checkbox createCheckbox() {
return new MacCheckbox();
}
}
// Client
class Application {
private Button button;
private Checkbox checkbox;
public Application(GUIFactory factory) {
button = factory.createButton();
checkbox = factory.createCheckbox();
}
public void paint() {
button.paint();
checkbox.paint();
}
}
// Usage
public class Demo {
public static void main(String[] args) {
GUIFactory factory;
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("win")) {
factory = new WindowsFactory();
} else {
factory = new MacFactory();
}
Application app = new Application(factory);
app.paint();
}
}
This approach allows for easy extension of the system with new product families without changing the client code.