Search code examples
javafactory-pattern

Design a theme factory


My application could have several theme, which just includes a bunch of constants. I was thinking using a factory to generate the theme and control constants for different theme in the factory class. Is this a good practice for the theme design?

class Theme {
  public static final float LINE_WIDTH = 1;
  public static final awt.Color SELECTED_LINE_COLOR = Color.YELLOW;
  public static final awt.Color LINE_COLOR = Color.WHITE;
  // some other constant variables or const objects
}

class ThemeFactory {

  public static Theme getWhiteTheme() {
    whiteTheme = new Theme();
    whiteTheme.LINE_WIDTH = 2;
    whiteTheme.SELECTED_LINE_COLOR = Color.RED;
    whiteTheme.LINE_COLOR = Color.BLACK;

    return whiteTheme;
  }

  public static Theme getBlackTheme() {
    return new Theme();  // Theme class default settings are for black theme.
  }

}


class MyApplication {

  Theme currentTheme;

  MyApplication() {

    // get theme settings from preference store
    if (themeSettingInPrefStore.isWhiteTheme) {
      currentTheme = ThemeFactory.getWhiteTheme();
    } else if (themeSettingInPrefStore.isBlackTheme) {
      currentTheme = ThemeFactory.getBlackTheme();
    }  

  }

}

Solution

  • No, it's not.

    Theme lacks abstraction, and members are public and static. What if some average programmer changes something while the application is running? The fact that you are returning new Theme() is useless.

    Extensibility also sucks^H^H^H^H^H is at peril here. What if tomorrow somebody wants a BlackAndWhite theme?

    Protect the theme with getters. Eliminate that ThemeFactory and transform it to a singleton or something (I know, some people go berserk when hearing the word sigleton). If the theme gets complicated, use Builder (GoF) to load it from your preference store.