추상화 팩토리 패턴

김대익·2022년 3월 29일

추상화 팩토리 패턴은 팩토리 클래스를 만들때
Light mode, Dark mode처럼 동작에서 공통되는 부분이 많을 경우
공통되는 부분을 추상 클래스로 만들어 상속시키는 패턴이다.

아래 코드에는 없지만 런타임동안 팩토리를 선택해야 할 경우 사용한다고 한다.

#Button abstract(interface) and its implementations
class Button:
  def click(self):
    pass

class DarkButton(Button):
  def click(self):
    print("dark click")

class LightButton(Button):
  def click(self):
    print("light click")
    
#UIFactory Abstract(interface) and its implementations
class UIFactory:
  def getButton(self):
    pass

class DarkUIFactory(UIFactory):
  def getButton(self):
    return DarkButton()

class LightUIFactory(UIFactory):
  def getButton(self):
    return LightButton()    
    
dark_factory = DarkUIFactory()
dark_btn = dark_factory.getButton()

JS에서 Employee, Vendor 팩토리를 선언하여 예를 들면

function Employee(name) {
    this.name = name;

    this.say = function () {
        console.log("I am employee " + name);
    };
}

function EmployeeFactory() {

    this.create = function (name) {
        return new Employee(name);
    };
}

function Vendor(name) {
    this.name = name;

    this.say = function () {
        console.log("I am vendor " + name);
    };
}

function VendorFactory() {

    this.create = function (name) {
        return new Vendor(name);
    };
}

function run() {
    var persons = [];
    var employeeFactory = new EmployeeFactory();
    var vendorFactory = new VendorFactory();

    persons.push(employeeFactory.create("Joan DiSilva"));
    persons.push(employeeFactory.create("Tim O'Neill"));
    persons.push(vendorFactory.create("Gerald Watson"));
    persons.push(vendorFactory.create("Nicole McNight"));

    for (var i = 0, len = persons.length; i < len; i++) {
        persons[i].say();
    }
}

new로 두 팩토리 객체를 만든 뒤 persons배열에 동적으로 객체를 추가하는 것을 볼 수 있다.

0개의 댓글