팩토리 메서드 패턴은
팩토리 패턴을 확장시킨 것으로
팩토리에 다른 함수(메서드)들을 추가할 수 있게 하는 패턴이다(팩토리함수의 상태관리, 생성한 객체의 개수 리턴)
class Animal():
def speak(self):
pass
class Cat(Animal):
def speak(self):
print("meow")
class Dog(Animal):
def speak(self):
print("bark")
class AnimalFactory():
def createAnimal(self):
pass
class CatFactory(AnimalFactory):
def __init__(self):
self.cat_count = 0
def createAnimal(self):
self.cat_count += 1
return Cat()
def catCount(self):
return self.cat_count
class DogManager(AnimalFactory):
def haveDog(self):
self.dog = self.createAnimal()
def createAnimal(self):
return Dog()
def makeWings(self,dog:Dog):
print("dog wings added")
return dog
cat_factory = CatFactory()
cat = cat_factory.createAnimal()
print(f"{cat_factory.catCount()} cats are created")
dog_manager = DogManager()
dog = dog_manager.haveDog()
wing_dog = dog_manager.makeWings(dog)
위와 같이 CatFactory 클래스 안에 catCount(self) 메서드를 넣거나
DogManger 클래스에 makeWings(self,dog:Dog) 메서드를 넣는 것 같이 메서드를 추가하는 것이다.
JS코드를 예로 들면
var Factory = function () {
this.createEmployee = function (type) {
var employee;
if (type === "fulltime") {
employee = new FullTime();
} else if (type === "parttime") {
employee = new PartTime();
} else if (type === "temporary") {
employee = new Temporary();
} else if (type === "contractor") {
employee = new Contractor();
}
employee.type = type;
employee.say = function () {
console.log(this.type + ": rate " + this.hourly + "/hour");
}
return employee;
}
}
var FullTime = function () {
this.hourly = "$12";
};
var PartTime = function () {
this.hourly = "$11";
};
var Temporary = function () {
this.hourly = "$10";
};
var Contractor = function () {
this.hourly = "$15";
};
function run() {
var employees = [];
var factory = new Factory();
employees.push(factory.createEmployee("fulltime"));
employees.push(factory.createEmployee("parttime"));
employees.push(factory.createEmployee("temporary"));
employees.push(factory.createEmployee("contractor"));
for (var i = 0, len = employees.length; i < len; i++) {
employees[i].say();
}
}
팩토리 함수안에
employee.say = function () {
console.log(this.type + ": rate " + this.hourly + "/hour");
}
say메서드를 생성한 것을 볼 수 있다.