Jump to content

[Tutorial] Decorating entities, an alternative to static libraries


Traum

Recommended Posts

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!

  • Like 3
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...