java - Avoiding code duplication when overriding abstract methods in enum -
i implementing state machine in enum in java. have toy example below, transition between x
,y
, z
states based on group membership.
the issue is, transition rule y
, z
identical (i.e., overriden methods identical).
is there way avoid code duplication here? in real life example, bit more severe code duplication potential worse.
enum group { a,b,c } enum element { x(group.a) { @override public element getnextelement(element nextelement) { if(nextelement.getgroup() == group.b) { return nextelement; } else { return this; } } }, y(group.b) { @override public element getnextelement(element nextelement) { if(nextelement.getgroup() == group.a) { return nextelement; } else { return this; } } }, z(group.c) { @override public element getnextelement(element nextelement) { if(nextelement.getgroup() == group.a) { return nextelement; } else { return this; } } }; group group; element(group group) { this.group=group; }; public group getgroup() { return this.group; } public abstract element getnextelement(element nextelement); }
you use strategy pattern, in following example. example improved thinking how different strategies relate each other , pulling similarities 1 or several strategy base classes:
enum element { interface transitionstrategy { element getnextelement (element myself, element nextelement); } static class nextonbstrategy implements transitionstrategy { element getnextelement (element myself, element nextelement) { if(nextelement.getgroup() == group.b) { return nextelement; } else { return myself; } } } // other strategies x(group.a, new nextonbstrategy ()), y(group.b, new nextonastrategy ()), z(group.c, new nextonastrategy ()); group group; transitionstrategy strategy; element(group group, transitionstrategy strategy) { this.group=group; this.strategy=strategy; }; // ... public element getnextelement(element nextelement) { return this.strategy.getnextelement (this, nextelement); } }
Comments
Post a Comment