Prototype Pattern Demo
package PrototypePatternDemo;
// Create an abstract base class implementing Clonable interface
abstract class GameCharacter implements Cloneable {
protected String characterType;
abstract void play();
public Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
package PrototypePatternDemo;
// Create concrete classes extending above class
class Warrior extends GameCharacter {
public Warrior() {
this.characterType = "Warrior";
}
@Override
void play() {
System.out.println("The Warrior is fighting");
}
}
package PrototypePatternDemo;
class Mage extends GameCharacter {
public Mage() {
this.characterType = "Mage";
}
@Override
void play() {
System.out.println("The Mage is casting spells");
}
}
Driver:
In this example, Warrior
and Mage
are concrete classes that extend GameCharacter
. The CharacterStore
class maintains a map of GameCharacter
instances, and when asked for a character of a specific type, it clones the corresponding character from the map. The PrototypePatternDemo
shows how to retrieve these cloned objects.
This approach allows for very efficient instantiation of complex objects, because instead of creating a new object from scratch, you can simply clone an existing instance.
COSC-1437 / ITSE-2457 Computer Science Dept. - Author: Dr. Kevin Roark