Traum Posted January 28, 2016 Share Posted January 28, 2016 Decorating entities, an alternative to static libraries I often see static libraries such as the following: public class CombatLibrary { private CombatLibrary() { } public static boolean attack(NPC target) { return target.interact("Attack"); } } Script call: CombatLibrary.attack(getNpcs().closest("Goblin")); It's fine, not very OO, but it works (for most things). However, let me introduce you to an arguably cleaner design by using the decorator pattern. First of, you'll need a utility class to wrap your NPCs , all decorator classes will extend this. We pass an existing NPC instance to the constructor. Our constructor calls NPC's constructor (NPCDecorator extends NPC, NPC is NPCDecorator's superclass) and passes it the NPC instance value's accessor value. public class NPCDecorator extends NPC { public NPCDecorator(NPC npc) { super(npc.accessor); } } Now let's make our first concrete decorator. We simply extend NPC decorator. We added a simple method calling a method of the NPC API with a specific parameter value. public class AttackableNPC extends NPCDecorator { public AttackableNPC(NPC npc) { super(npc); } public boolean attack() { return interact("Attack"); } } Script call: new AttackableNPC(getNpcs().closest("Goblin")).attack(); The provided implementation is very simple and does not provide more functionality than the static library method (as is). But it could be so much more, this design allows for OO (inheritance, polymorphism,etc..) among other things. I might write up a more complex implementation to demonstrate it's full power in the future! 3 Quote Link to comment Share on other sites More sharing options...
Chris Posted January 28, 2016 Share Posted January 28, 2016 Very nice read Quote Link to comment Share on other sites More sharing options...
Diclonius Posted January 28, 2016 Share Posted January 28, 2016 Nice. Surprisingly never thought of doing this. Quote Link to comment Share on other sites More sharing options...
Flamezzz Posted January 28, 2016 Share Posted January 28, 2016 That's a nice solution, although I don't like how decorators can be abused and add unnecessary complexity (java IO ) Quote Link to comment Share on other sites More sharing options...