Design patterns

patterns3AbstractFactoryPattern

Path
pkg8patterns/patterns3AbstractFactoryPattern.java
Package
pkg8patterns
Study order
3
Run
Single-file source launch
Command
java pkg8patterns/patterns3AbstractFactoryPattern.java

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg8patterns/patterns3AbstractFactoryPattern.java
1package pkg8patterns;2 3/*4 * Abstract Factory (Creational)5 * -----------------------------6 * INTENT: provide an interface for creating FAMILIES of related objects without7 *         specifying their concrete classes.8 * UML: AbstractFactory + createA(): A + createB(): B ; concrete factories per family.9 * PROS: guarantees products from one family are used together; easy to swap families.10 * CONS: adding a new product type requires changing every factory.11 * REAL-WORLD: cross-platform UI toolkits (Windows vs Mac widgets).12 */13public class patterns3AbstractFactoryPattern {14 15    interface Button { String render(); }16    interface Checkbox { String render(); }17 18    static class WinButton implements Button { public String render() { return "[Windows Button]"; } }19    static class WinCheckbox implements Checkbox { public String render() { return "[Windows Checkbox]"; } }20    static class MacButton implements Button { public String render() { return "(Mac Button)"; } }21    static class MacCheckbox implements Checkbox { public String render() { return "(Mac Checkbox)"; } }22 23    interface GuiFactory { Button button(); Checkbox checkbox(); }24    static class WinFactory implements GuiFactory {25        public Button button() { return new WinButton(); }26        public Checkbox checkbox() { return new WinCheckbox(); }27    }28    static class MacFactory implements GuiFactory {29        public Button button() { return new MacButton(); }30        public Checkbox checkbox() { return new MacCheckbox(); }31    }32 33    static void renderUI(GuiFactory factory) {34        System.out.println(factory.button().render() + " " + factory.checkbox().render());35    }36 37    public static void main(String[] args) {38        System.out.print("Windows UI: "); renderUI(new WinFactory());39        System.out.print("Mac UI:     "); renderUI(new MacFactory());40    }41}