Programing/Design Patterns

Factory Method Pattern 팩토리메서드 패턴 GoF 디자인패턴

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

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

 

특징

팩토리 메서드 패턴 (Factory Method Pattern)은 객체 생성에 관련된 디자인 패턴 중의 하나로, 

객체의 생성을 서브클래스로 분리하여 객체를 생성하는 방식을 추상화 하는데 사용됩니다.

추상화된 팩토리 클래스에 대한 인터페이스를 제공하고, 이를 구체화하여 서브클래스에서 실제 객체를 생성하는 메서드를 구현(캡슐화)합니다. 이를 통해 객체 생성 로직을 클라이언트로부터 분리하고, 유연성과 확장성을 제공합니다.

 

샘플코드

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;
    }
}

[추상화 Factory class]

public abstract class ResponseFactory {
    abstract CommonResponse createResponse();

    public void getResponse(){
        CommonResponse response = createResponse();
        response.getData();
    }
}

추상클래스인 ResponseFactory 를 구체화 하여 서브 클래스인 JpaFactory, MybatisFactory 생성합니다.

public class JpaFactory extends ResponseFactory {

    @Override
    CommonResponse createResponse() {
        return new JpaResponse();
    }
}
public class MybatisFactory extends ResponseFactory {

    @Override
    CommonResponse createResponse() {
        return new MybatisResponse();
    }
}

 

public class FactoryMethodPattern {
    public static void main(String args[]) {
        ResponseFactory factory = new JpaFactory();
        factory.getResponse();

        factory = new MybatisFactory();
        factory.getResponse();
    }
}

 

실행결과

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

 

CommonResponse 를 구현한 JpaResponse, MybatisResponse 를 생성합니다.

추상 클래스인 ResponseFactory는 createResponse를 추상 클래스로 선언하고 getResponse메서드에서는 createResponse로 생성한 CommponResponse의 getData Method를 실행하게 합니다.

 

이제 JpaFactory에서는 JpaResponse의 getData를, MybatisFactory에서는 MybatisResponse의 getData를 호출하게 됩니다.

 

Abstract Factory Pattern과 Factory Method Pattern이 비슷해 보이는데, 그 차이를 알아봅시다.

 

추상 팩토리 패턴과 팩토리 메서드 패턴의 차이

  Abstract Factory Pattern Factory Method Pattern
목적 관련된 객체들의 팩토리를 생성하여 객체를 그룹화 객체 생성을 서브 클래스로 분리하여 객체 생성 방식을 추상화
구현 여러개의 연관된 객체들을 생성하는 팩토리 클래스 계층 구조를 사용 서브 클래스에서 객체 생성을 처리하는 방식으로 구현
적합한 활용 그룹 생성 및 관리 단일 객체 생성

 

 

 

반응형

댓글

💲 추천 글