Abstract Factory Pattern은 객체를 생성하기 위한 디자인 패턴 중 하나로, 다양한 종류의 객체를 생성하기 위한 것입니다. 이 디자인 패턴은 객체 생성을 추상화하고, 객체의 생성과 조합을 쉽게 만들 수 있도록 합니다. 이번 글에서는 Abstract Factory Pattern의 개념과 구현 방법에 대해 자세히 알아보도록 하겠습니다.

Abstract Factory Pattern란 무엇인가?

Abstract Factory Pattern은 객체를 생성하기 위한 디자인 패턴입니다. 이 디자인 패턴은 객체 생성을 추상화하고, 객체의 생성과 조합을 쉽게 만들 수 있도록 합니다. 이는 객체 생성을 단순화하고, 코드의 유연성을 높여주는 역할을 합니다. 예를 들어, 객체의 생성과 조합을 쉽게 만들 수 있다면, 새로운 객체를 추가할 때, 기존 코드를 수정할 필요가 없이 새로운 객체를 만들 수 있습니다.

객체 생성을 위한 다양한 팩토리 구현 방법

Abstract Factory Pattern은 객체 생성을 추상화하기 때문에, 객체를 생성하는 다양한 방법을 사용할 수 있습니다. 예를 들어, 각각의 팩토리 메서드를 사용하여 객체를 생성하는 팩토리 메서드 패턴을 사용할 수 있습니다. 또한, 객체 생성을 위해 추상 팩토리를 사용할 수도 있습니다. 이는 팩토리 메서드 패턴의 확장된 개념으로, 서로 관련된 객체들을 생성하는 팩토리를 만들 수 있도록 합니다.

public interface Shape {
    void draw();
}

public class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Rectangle::draw() method.");
    }
}

public class Square implements Shape {
    @Override
    public void draw() {
        System.out.println("Square::draw() method.");
    }
}

public interface AbstractFactory {
    Shape createShape();
}

public class RectangleFactory implements AbstractFactory {
    @Override
    public Shape createShape() {
        return new Rectangle();
    }
}

public class SquareFactory implements AbstractFactory {
    @Override
    public Shape createShape() {
        return new Square();
    }
}

public class FactoryProducer {
    public static AbstractFactory getFactory(boolean isRectangle) {
        if (isRectangle) {
            return new RectangleFactory();
        } else {
            return new SquareFactory();
        }
    }
}

public class Main {
    public static void main(String[] args) {
        AbstractFactory rectangleFactory = FactoryProducer.getFactory(true);
        Shape rectangle = rectangleFactory.createShape();
        rectangle.draw();

        AbstractFactory squareFactory = FactoryProducer.getFactory(false);
        Shape square = squareFactory.createShape();
        square.draw();
    }
}

위 예제에서는 Shape 인터페이스를 상속받는 Rectangle과 Square 클래스를 만들어서, 이를 생성하는 팩토리 클래스를 만들었습니다. 이렇게 만들어진 팩토리 클래스는 AbstractFactory 인터페이스를 구현하고 있어, createShape() 메서드를 만들어서 객체를 생성할 수 있습니다. 이를 통해, Abstract Factory Pattern을 통해 다양한 종류의 객체를 생성할 수 있습니다.

Abstract Factory Pattern은 객체를 생성하기 위한 디자인 패턴 중 하나로, 다양한 종류의 객체를 생성하기 위한 것입니다. 이 디자인 패턴은 객체 생성을 추상화하고, 객체의 생성과 조합을 쉽게 만들 수 있도록 합니다. 이는 객체 생성을 단순화하고, 코드의 유연성을 높여주는 역할을 합니다. 이 글을 통해, Abstract Factory Pattern의 개념과 구현 방법에 대해 자세히 알아보았습니다.

Reference : Abstract Factory Pattern: 다양한 종류의 객체를 생성하기 위한 디자인 패턴

+ Recent posts