DEV Community

Prashant Mishra
Prashant Mishra

Posted on • Updated on

Abstract factory method

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

Image description


//abstract product
public interface Button {
    public void print();
}
Enter fullscreen mode Exit fullscreen mode
// concrete product 1
public class MacButton implements Button {

    @Override
    public void print() {
        System.out.println("Render button for mac");
    }

}
Enter fullscreen mode Exit fullscreen mode
//concreate product for windows 2
public class WindowsButton implements Button{

    @Override
    public void print() {
        System.out.println("Render button for windows");
    }

}
Enter fullscreen mode Exit fullscreen mode
//abstract factory
public interface GUIFactory {
    public Button createBtton();
}
Enter fullscreen mode Exit fullscreen mode
//concreate implementation of abstract factory (family windows)
public class WindowsFactory implements GUIFactory {

    @Override
    public Button createBtton() {
        return new WindowsButton();
    }

}
Enter fullscreen mode Exit fullscreen mode
//concreate implementation of abstract factory (family mac)
public class MacFactory implements GUIFactory{

    @Override
    public Button createBtton() {
        return new MacButton();
    }

}
Enter fullscreen mode Exit fullscreen mode
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();
    }
}
Enter fullscreen mode Exit fullscreen mode

output:

Render button for windows

Top comments (0)