Programing/Design Patterns

Abstract Factory Pattern 추상팩토리 패턴 GoF 디자인패턴

리커니 2023. 7. 12.
반응형

GoF 디자인 패턴 중 생성패턴의 하나인 Abstract Factory 패턴에 대해 알아보도록 하겠습니다.

 

특징

추상 팩토리 패턴 (Abstract Factory Pattern)은 객체 생성에 관련된 디자인 패턴 중의 하나로,

관련된 객체들의 팩토리를 생성하기 위한 인터페이스를 제공하며, 이 팩토리를 사용하여 서로 다른 객체들의 그룹을 생성할 수 있습니다. 객체들의 생성로직을 클라이언트로부터 분리하여 객체 간 결합도를 낮추고, 유연성과 확장성을 높이는데 사용됩니다.

 

샘플코드

Jpa와 Mybatis로 응답을 받는 2개의 추상 객체를 정의하고, 각각 응답에 대한 로직을 구현한 구체적인 객체를 생성하는 팩토리를 만들어보겠습니다.

public interface CommonResponse {
    Object getData();
}
public class JpaResponse implements CommonResponse {

    @Override
    public Object getData() {
        /**jpa로 데이터를 조회하는 로직 구현 */
        System.out.println("Jpa로 데이터를 조회");
        return null;
    }
}
public class MybatisResponse implements CommonResponse {

    @Override
    public Object getData() {
        /**mybatis로 데이터를 조회하는 로직 구현 */
        System.out.println("Mybatis로 데이터를 조회");
        return null;
    }
}

CommonResponse 추상 객체로 구체화한 JpaResponse와 MybatisResponse를 구현합니다.

public interface CommonResponseFactory {
    CommonResponse getResponse();
}
public class JpaFactory implements CommonResponseFactory {

    @Override
    public CommonResponse getResponse() {
        return new JpaResponse();
    }
}
public class MybatisFactory implements CommonResponseFactory {

    @Override
    public CommonResponse getResponse() {
        return new MybatisResponse();
    }
}

CommonResponseFactory는 추상 팩토리이며 이를 구체화 한 JpaFactory와 MybatisFactory를 구현합니다.

각 Factory는 getResponse() 메서드를 통해 해당하는 응답의 구체적인 객체를 생성합니다.

 

public class AbstractFactory {
    public static void main(String args[]) {
        CommonResponseFactory factory = new JpaFactory();
        CommonResponse jpaResponse = factory.getResponse();
        jpaResponse.getData();

        factory = new MybatisFactory();
        CommonResponse mybatisResponse = factory.getResponse();
        mybatisResponse.getData();
    }
}

실행결과

Jpa로 데이터를 조회
Mybatis로 데이터를 조회

 

이제 구체화한 Factory를 사용해서 CommonResponse 객체를 생성하고 데이터를 조회하는 getData() 메서드를 호출합니다.

이렇게 추상 팩토리 패턴을 쓰면 객체를 생성하는 과정을 추상화된 인터페이스를 통해 수행하고, 객체의 실제 구현은 사용자로부터 분리됩니다. 이는 사용자의 코드 유연성과 확장성을 높여주게 됩니다.

 

반응형

댓글

💲 추천 글