Sie sind auf Seite 1von 2

Hierarchical structures with Java ...

11/10/2010 20:29 1 de 2

Hierarchical structures with Java Enums


October 9th, 2010

I love Enums. There are a lot of use cases, where they become really handy. Especially since I have
learned that you can override methods in enums…

Some days ago Alexander Radzin came up with another nice idea ( http://alexradzin.blogspot.com/2010/10
/hierarchical-structures-with-java-enums_05.html ) : He created a hierarchical structure using enums. The
idea is very simple: Just add a reference to the parent to your enum.

While the idea is really nice, the implementation seems to be a little bit too complicated. I think using
reflection is not a very nice thing at all. Therefore I have modified his implementation.

And this is the idea. That idea has a lot of potential – I am sure I will find a lot of nice use cases…

public enum OsType {


OS(null),
Windows(OS),
WindowsNT(Windows),
WindowsNTWorkstation(WindowsNT),
WindowsNTServer(WindowsNT),
Windows2000(Windows),
Windows2000Server(Windows2000),
Windows2000Workstation(Windows2000),
WindowsXp(Windows),
WindowsVista(Windows),
Windows7(Windows),
Windows95(Windows),
Windows98(Windows),
Unix(OS) {
@Override
public boolean supportsXWindowSystem() {
return true;
}
},
Linux(Unix),
AIX(Unix),
HpUx(Unix),
SunOs(Unix),
;

private final OsType parent;


private final List<OsType> children = new ArrayList<OsType>();
private final List<OsType> allChildren = new ArrayList<OsType>();

OsType( OsType parent ) {


this.parent = parent;
if ( parent != null ) {
parent.addChild( this );
}
}

public OsType parent() {


return parent;
}

public boolean is( OsType other ) {


if ( other == null ) {
return false;

http://blog.cedarsoft.com/2010/10/hierarchical-structures-with-java-enums/
Hierarchical structures with Java ... 11/10/2010 20:29 2 de 2

for ( OsType osType = this; osType != null; osType = osType.parent() ) {


if ( other == osType ) {
return true;
}
}
return false;
}

public List<? extends OsType> children() {


return Collections.unmodifiableList( children );
}

public List<? extends OsType> allChildren() {


return Collections.unmodifiableList( allChildren );
}

private void addChild( OsType child ) {


this.children.add( child );

List<OsType> greatChildren = new ArrayList<OsType>();


greatChildren.add( child );
greatChildren.addAll( child.allChildren() );

OsType currentAncestor = this;


while ( currentAncestor != null ) {
currentAncestor.allChildren.addAll( greatChildren );
currentAncestor = currentAncestor.parent;
}
}

public boolean supportsXWindowSystem() {


if ( parent == null ) {
return false;
}

return parent.supportsXWindowSystem();
}
}

http://blog.cedarsoft.com/2010/10/hierarchical-structures-with-java-enums/