[php] 팩토리 클래스

팩토리 클래스는 객체를 생성하는 데 사용되는 디자인 패턴입니다. 이 패턴은 객체를 생성하는 로직을 캡슐화하여 클래스 인스턴스화 코드로부터 분리하는 데 유용합니다. 이것은 코드 의존성을 줄이고 유연성을 증가시킵니다.

팩토리 클래스는 다음과 같은 상황에서 사용되어집니다:

팩토리 클래스의 예시

다음은 PHP에서 팩토리 클래스를 구현하는 간단한 예시입니다.

<?php

interface Shape {
    public function draw();
}

class Rectangle implements Shape {
    public function draw() {
        echo "Inside Rectangle::draw() method.";
    }
}

class Square implements Shape {
    public function draw() {
        echo "Inside Square::draw() method.";
    }
}

class ShapeFactory {
    public function getShape($shapeType) {
        if ($shapeType == "RECTANGLE") {
            return new Rectangle();
        } else if ($shapeType == "SQUARE") {
            return new Square();
        }
        return null;
    }
}

$shapeFactory = new ShapeFactory();

// get an object of Rectangle and call its draw method.
$shape1 = $shapeFactory->getShape("RECTANGLE");
$shape1->draw();

// get an object of Square and call its draw method.
$shape2 = $shapeFactory->getShape("SQUARE");
$shape2->draw();

?>

위 코드에서, ShapeFactory 클래스는 getShape 메서드를 사용하여 Shape 객체를 생성합니다. 이를 통해 호출자는 구체적인 객체 생성 로직을 알 필요가 없으며, 단지 ShapeFactory 클래스의 메서드를 호출함으로써 객체를 얻을 수 있습니다.

팩토리 클래스 패턴은 객체지향 디자인의 많은 측면에서 사용되며, 이를 통해 코드의 재사용성, 유지보수성 및 가독성을 향상시킬 수 있습니다.

참고 자료