Flyweight Enum

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

* Use integers to represent enums. A dummy class is declared to contain the range; and a bunch of static final int declarations are in the class body, each encoding one of the cases. i.e.

 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.

* Use flyweight objects to represent enums. A flyweight object is one that has no internal state (though in Java it will have a built-in monitor, a couple scratchpad registers for the GarbageCollector, etc). An abstract base class represents the set; a set of derived concrete classes represents the individual members in the set. Like this:

 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:

* If a function is declared to take a MaritalStatus, it will accept only a MaritalStatus. (Or null--you can't eliminate this possibility unfortunately). But you can keep someone from passing in an EthnicGroup or a string length or some other unrelated quantity.

* Since the enums are full-fledged objects rather than ints, they can be stuffed into containers, have their names printable by the program (provide a toString method), introspected, etc.

* No need to worry about the numbers assigned to each case; no chance of duplicating one.

Disadvantages:

* It is hard to provide a TotallyOrdered set. The < and > operators will not work.

* More typing needed.


DesignPattern JavaIdiom


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

This page mirrored in JavaIdioms as of October 22, 2005