


Definition: The prototype pattern allows you to create new objects by copying an existing "prototype" object.
Usage: Use the prototype pattern when creating an instance of a class is either too expensive or complicated.
class NPC {
NPC(String imageFilename, String aiFilename, String scriptFilename) {
this.images = loadImages(imageFilename);
this.ai = loadAi(aiFilename);
this.script = loadScript(scriptFilename);
}
NPC(Images images, Ai ai, Script script) {
this.images = images;
this.ai = ai;
this.script = script;
}
NPC clone(String scriptFilename) {
return new NPC(images, ai, loadScript(scriptFilename));
}
Images images;
Ai ai;
Script script;
}
class NPCRegistry {
NPCRegistry() {
aNPCTemplate = {
new NPC(imageFilename0, aiFilename0, scriptFilename0),
new NPC(imageFilename1, aiFilename1, scriptFilename1),
...
new NPC(imageFilenameN, aiFilenameN, scriptFilenameN)
}
}
NPC createNPC(int iTemplate, String scriptFilename) {
return aNPCTemplate[iTemplate].clone(scriptFilename);
}
NPC[] aNPCTemplate;
}
The first NPC should be created with the first constructor, which loads everything. There will probably be other NPCs who look and act the same, but say different things. To create NPCs like this, just call the clone method. This saves loading new images and ai, which would consume both time and memory.
NPCRegistry does this, though it would be alot cooler if it had lazy initialization and such.
Copyright (C) 2008 Steven Fletcher. All rights reserved.