This content originally appeared on DEV Community and was authored by Prashant Mishra
It is part of creational design pattern, used to create factory of factories
It is used when we want to create objects of products of different family
Structure:
Product: Defines the interface for objects the factory method creates.
ConcreteProduct: Implements the Product interface.
Creator: Declares the factory method, which returns an object of type Product.
ConcreteCreator: Overrides the factory method to return an instance of a ConcreteProduct.
Let us understand this with an example:
Suppose you're developing a UI toolkit that should work on different operating systems. You could use the Abstract Factory Pattern to ensure that the toolkit creates the appropriate UI components based on the operating system.
Let's render Button on UI for different OS(s) like Mac and windows
//abstract product
public interface Button {
public void print();
}
// concrete product 1
public class MacButton implements Button {
@Override
public void print() {
System.out.println("Render button for mac");
}
}
//concreate product for windows 2
public class WindowsButton implements Button{
@Override
public void print() {
System.out.println("Render button for windows");
}
}
//abstract factory
public interface GUIFactory {
public Button createBtton();
}
//concreate implementation of abstract factory (family windows)
public class WindowsFactory implements GUIFactory {
@Override
public Button createBtton() {
return new WindowsButton();
}
}
//concreate implementation of abstract factory (family mac)
public class MacFactory implements GUIFactory{
@Override
public Button createBtton() {
return new MacButton();
}
}
public class Application {
Button button;
public Application(GUIFactory factory){
this.button = factory.createBtton();
}
public static void main(String args[]){
GUIFactory factory = new WindowsFactory(); // or new MacFactory();
Application application = new Application(factory);
application.print();
}
public void print(){
button.print();
}
}
output:
Render button for windows
This content originally appeared on DEV Community and was authored by Prashant Mishra
Prashant Mishra | Sciencx (2024-08-26T15:54:10+00:00) Abstract factory method. Retrieved from https://www.scien.cx/2024/08/26/abstract-factory-method/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.