프로토타입 패턴 (Prototype Pattern)
기본 원형이 되는 인스턴스를 사용해서 생성할 객체의 종류를 명시하고 이렇게 만들어진 객체를 복사해서 새로운 객체를 생성하는 패턴
89 : 핵심은 어떤 객체가 자기와 비슷한 객체를 스폰할 수 있다는 점이다.
public abstract class Monster {
int health_, speed_;
Monster(int health, int speed) {
this.health_ = health;
this.speed_ = speed;
}
public abstract Monster clone() throws CloneNotSupportedException;
public void print() {
System.out.println(this.getClass() + " health_ = " + health_ + " speed_ = " + speed_);
}
}
public class Ghost extends Monster {
public Ghost(int health, int speed) {
super(health, speed);
}
@Override
public Monster clone() throws CloneNotSupportedException {
return new Ghost(health_, speed_);
}
}
public class Demon extends Monster {
public Demon(int health, int speed) {
super(health, speed);
}
@Override
public Monster clone() throws CloneNotSupportedException {
return new Demon(health_, speed_);
}
}
public class Sorcerer extends Monster {
public Sorcerer(int health, int speed) {
super(health, speed);
}
@Override
public Monster clone() throws CloneNotSupportedException {
return new Sorcerer(health_, speed_);
}
}
public class Spawner {
private final Monster monster;
public Spawner(Monster monster) {
this.monster = monster;
}
public Monster spawn() throws CloneNotSupportedException {
return monster.clone();
}
}
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
Demon demon = new Demon(15, 15);
Spawner demonSpawner = new Spawner(demon);
Ghost ghost = new Ghost(5, 20);
Spawner ghostSpawner = new Spawner(ghost);
Sorcerer sorcerer = new Sorcerer(20, 10);
Spawner sorcererSpawner = new Spawner(sorcerer);
demonSpawner.spawn().print();
ghostSpawner.spawn().print();
sorcererSpawner.spawn().print();
}
}
// 실행결과
class prototype.Demon health_ = 15 speed_ = 15
class prototype.Ghost health_ = 5 speed_ = 20
class prototype.Sorcerer health_ = 20 speed_ = 10'Computer Science > Design Pattern' 카테고리의 다른 글
| [게임 프로그래밍 패턴] 6. 상태 패턴 (0) | 2023.11.13 |
|---|---|
| [게임 프로그래밍 패턴] 5. 싱글턴 패턴 (0) | 2023.11.13 |
| [게임 프로그래밍 패턴] 3. 관찰자 패턴 (0) | 2023.10.30 |
| [게임 프로그래밍 패턴] 2. 경량 패턴 (0) | 2023.10.27 |
| [게임 프로그래밍 패턴] 1. 명령 패턴 (1) | 2023.10.14 |