HIT해

[Swift 기초문법 - 69] 팩토리 메서드 패턴 본문

Swift/Swift 기초문법

[Swift 기초문법 - 69] 팩토리 메서드 패턴

힛해 2024. 8. 24. 01:31
728x90

팩토리 메서드 패턴이란?

팩토리 메서드 패턴은 객체 생성 로직을 캡슐화하여 객체의 생성과 관련된 책임을 다른 객체로 위임하는 디자인 패턴이다.

Swfit에서는 클래스나 구조체의 정적 메서드 (static method)를 사용하여 팩토리 메서드를 구현할 수 있다.

이를 통해 객체 생성 과정을 숨기고, 객체 생성 로직을 중앙 집중화할 수 있다.

 

팩토리 메서드 기본 개념

팩토리 메서드는 객체를 생성하는 역할을 담당하는 메서드로, 클래스나 구조체의 인스턴스를 생성하는 복잡한 로직을 메서드 내에서 처리한다. 

이를 통해 객체 생성의 유연성과 재사용성을 높일 수 있다.

 

팩토리 메서드 구현 예제

class Vehicle {
    let type: String
    let numberOfWheels: Int
    
    // 기본 생성자
    init(type: String, numberOfWheels: Int) {
        self.type = type
        self.numberOfWheels = numberOfWheels
    }
    
    // 팩토리 메서드
    static func createCar() -> Vehicle {
        return Vehicle(type: "Car", numberOfWheels: 4)
    }
    
    static func createBike() -> Vehicle {
        return Vehicle(type: "Bike", numberOfWheels: 2)
    }
}

// 팩토리 메서드를 통해 객체 생성
let car = Vehicle.createCar()
let bike = Vehicle.createBike()

print("Vehicle type: \(car.type), Wheels: \(car.numberOfWheels)")  // 출력: Vehicle type: Car, Wheels: 4
print("Vehicle type: \(bike.type), Wheels: \(bike.numberOfWheels)")  // 출력: Vehicle type: Bike, Wheels: 2

 

위와같이 생성 로직을 클래스 내부에 정의하여 인스턴스를 생성하면서 정의하지않고 함수 호출로 생성할 수 있다.

 

구조체에서도 마찬가지로 구현이 가능하다.

struct Rectangle {
    let width: Double
    let height: Double
    
    // 팩토리 메서드
    static func createSquare(side: Double) -> Rectangle {
        return Rectangle(width: side, height: side)
    }
    
    static func createRectangle(width: Double, height: Double) -> Rectangle {
        return Rectangle(width: width, height: height)
    }
}

// 팩토리 메서드를 통해 객체 생성
let square = Rectangle.createSquare(side: 10.0)
let rectangle = Rectangle.createRectangle(width: 10.0, height: 20.0)

print("Square width: \(square.width), height: \(square.height)")  // 출력: Square width: 10.0, height: 10.0
print("Rectangle width: \(rectangle.width), height: \(rectangle.height)")  // 출력: Rectangle width: 10.0, height: 20.0

 

 

팩토리 메서드 장점

  • 캡슐화 : 객체 생성 로직을 클래스나 구조체 내부에 숨길 수 있다. 이를 통해 클라이언트 코드는 객체 생성 방식에 대해 알 필요가 없으며 객체 생성 방식을 변경할때도 클라이언트 코드를 수정할 필요가 없어진다.
  • 유연성 : 객체 생성 로직을 중앙 집중화 함으로써 다양한 타입의 객체를 생성할 수 있는 유연성을 제공한다
  • 재사용성 : 복잡한 객체 생성 로직을 재사용할 수 있으며, 코드 중복을 줄일 수 있다.