// Base class for all characters
class Character {
constructor(name, strength, defense) {
this.name = name;
this.strength = strength;
this.defense = defense;
}
attack() {
console.log(`${this.name} attacks for ${this.strength} damage.`);
}
defend() {
console.log(`${this.name} defends with ${this.defense} strength.`);
}
}
// Factory class for creating characters
class CharacterFactory {
createCharacter(type, name) {
switch(type) {
case 'warrior':
return new Warrior(name);
case 'mage':
return new Mage(name);
case 'rogue':
return new Rogue(name);
default:
throw new Error(`Unsupported character type: ${type}`);
}
}
}
// Concrete classes for each type of character
class Warrior extends Character {
constructor(name) {
super(name, 10, 5);
}
}
class Mage extends Character {
constructor(name) {
super(name, 5, 10);
}
}
class Rogue extends Character {
constructor(name) {
super(name, 8, 8);
}
}
// Usage example
const factory = new CharacterFactory();
const player1 = factory.createCharacter('warrior', 'John');
const player2 = factory.createCharacter('mage', 'Jane');
const player3 = factory.createCharacter('rogue', 'Bob');
player1.attack();
player2.defend();
player3.attack();