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.
1
2
3
public interface WindowFactory {
    Window createWindow(); // implicitly public
}
1
2
3
4
5
public MsWindowFactory implements WindowFactory {
    @Override public Window createWindow() {
        return new MsWindow();
    }
}
1
2
3
4
5
public AppleWindowFactory implements WindowFactory {
    @Override public Window createWindow() {
        return new AppleWindow();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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();
    }
}