[swift] 클래스의 팩토리 메서드(Factory Method) 패턴

팩토리 메서드 패턴은 객체 생성을 담당하는 디자인 패턴 중 하나입니다. 이 패턴은 객체를 생성하는 인터페이스를 정의하지만, 구체적인 클래스는 서브클래스에게 미루는 것이 특징입니다.

팩토리 메서드 패턴의 구조

팩토리 메서드 패턴은 다음과 같은 구조를 가집니다.

  1. Creator: 객체 생성을 위한 인터페이스를 정의합니다.
  2. ConcreteCreator: 구체적인 객체 생성 방법을 결정하는 클래스입니다.
  3. Product: 생성될 객체의 인터페이스를 정의합니다.
  4. ConcreteProduct: 구체적으로 생성되는 객체를 나타내는 클래스입니다.

Swift에서 팩토리 메서드 패턴 구현

// Product
protocol Animal {
    func makeSound()
}

// ConcreteProduct
class Dog: Animal {
    func makeSound() {
        print("멍멍")
    }
}

class Cat: Animal {
    func makeSound() {
        print("야옹")
    }
}

// Creator
protocol AnimalFactory {
    func create() -> Animal
}

// ConcreteCreator
class DogFactory: AnimalFactory {
    func create() -> Animal {
        return Dog()
    }
}

class CatFactory: AnimalFactory {
    func create() -> Animal {
        return Cat()
    }
}

// Usage
let dogFactory = DogFactory()
let dog = dogFactory.create()
dog.makeSound()  // 출력: "멍멍"

let catFactory = CatFactory()
let cat = catFactory.create()
cat.makeSound()  // 출력: "야옹"

위 예제에서 Animal은 Product에 해당하며, DogCat은 ConcreteProduct에 해당합니다. AnimalFactory는 Creator, 그리고 DogFactoryCatFactory는 ConcreteCreator에 해당합니다.

팩토리 메서드 패턴의 장점

팩토리 메서드 패턴은 객체 생성 코드의 복잡성을 줄이고 유연한 코드를 작성할 수 있도록 도와줍니다. Swift를 포함한 다양한 프로그래밍 언어에서 이 패턴을 활용하여 유지보수가 용이하고 확장 가능한 소프트웨어를 개발할 수 있습니다.

참고문헌: Design Patterns: Elements of Reusable Object-Oriented Software