Tuesday, January 24, 2012

The Abstract Factory pattern

Problem: Instantiate families of objects.
Solution: The Abstract Factory pattern defines the interface for how to create each member of the family.
public interface WindowFactory {
    Window createWindow(); // implicitly public
}
public MsWindowFactory implements WindowFactory {
    @Override public Window createWindow() {
        return new MsWindow();
    }
}
public AppleWindowFactory implements WindowFactory {
    @Override public Window createWindow() {
        return new AppleWindow();
    }
}
public Client {
    public static void main(String[] args) {

        WindowFactory  factory;
        String osName = System.getProperty("os.name");
        if ((osName != null) && (osName.indexOf("Windows") != -1)) {
            factory = new MsWindowFactory();
        } else {
            factory = new AppleWindowFactory();
        }

        Window window = factory.createWindow();
    }
}