DEV Community

Rory Preddy
Rory Preddy

Posted on

Pattern of the Week:AbstractFactory

Type: Creational

Purpose: Provides a way to encapsulate a group of individual factories that have a common theme

Related Patterns:
• Factory
• Prototype (configure factory dynamically)
• Singleton (1 Abstract Factory)

We have a requirement where we need to create control library and the same library supports multiple platforms but the client code should not be changed if we import from one operating system to the other. The solution is

The client uses the GuiFactory to get the required factory of the supported operating system and calls the same Show Method. Now depending on the platform we change the factory but the client implementation remains the same. If support for new operating system is to be added we need the new factory and the exact implementation of the buttons and without changing the existing code we can support the new platform

/* GUIFactory example -- */

interface GUIFactory {
    public Button createButton();
}


class WinFactory implements GUIFactory {
    public Button createButton() {
        return new WinButton();
    }
}


class OSXFactory implements GUIFactory {
    public Button createButton() {
        return new OSXButton();
    }
}



interface Button {
    public void paint();
}


class WinButton implements Button {
    public void paint() {
        System.out.println("I'm a WinButton");
    }
}


class OSXButton implements Button {
    public void paint() {
        System.out.println("I'm an OSXButton");
    }
}


class Application {
    public Application(GUIFactory factory){
        Button button = factory.createButton();
        button.paint();
    }
}

public class ApplicationRunner {
    public static void main(String[] args) {
        new Application(createOsSpecificFactory());
    }

    public static GUIFactory createOsSpecificFactory() {
        int sys = readFromConfigFile("OS_TYPE");
        if (sys == 0) {
            return new WinFactory();
        } else {
            return new OSXFactory();
        }
    }

}

(Code example courtesy of http://en.wikipedia.org/wiki/Abstract_factory_pattern)

Top comments (0)