Flyweight Enum

One of the JavaDesignFlaws (pre 1.5) is the absence of enumerated types. There are several workarounds for this, including:

 class MaritalStatus {
    public static final int single = 0;
    public static final int married = 1;
    public static final int divorced = 2;
    public static final int widowed = 3;

This works, but has liabilities discussed in UseEnumsNotNumbers and UseEnumsNotBooleans. A better (though it takes more typing) solution is.

 abstract class MaritalStatus {
     class final Single_T extends MaritalStatus {}
     class final Married_T extends MaritalStatus {}
     class final Divorced_T extends MaritalStatus {}
     class final Widowed_T extends MaritalStatus {}

public Single_T single = new Single_T; public Married_T married = new Married_T; public Divorced_T divorced = new Divorced_T; public Widowed_T widowed = new Widowed_T; }

The paranoid might want to add dummy constructors to make sure no other instances of MaritalStatus (or its children) are created by the application.

The enum system in JDK 1.5 is quite similar to the above, IIRC



DesignPattern JavaIdiom

View edit of November 29, 2011 or FindPage with title or text search