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 married = new Divorced_T; public Widowed_T married = 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

Advantages:

Disadvantages:


DesignPattern JavaIdiom


EditText of this page (last edited September 10, 2004)
FindPage by browsing or searching

This page mirrored in JavaIdioms as of April 29, 2006