Jump to content

[Tutorial] Decorating entities, an alternative to static libraries


Recommended Posts

Posted

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

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