본문 바로가기
프로그래밍/디자인패턴

자바 팩토리 메서드 패턴

by 방구석개발자 2022. 10. 25.
반응형

출처: 위키백과

설명

팩토리 메소드 패턴은 객체를 생성할 때 어떤 클래스의 인스턴스를 만들지 서브 클래스에서 결정하게 합니다.

즉, 인스턴스 생성을 서브 클래스에게 위임합니다.

객체를 생성하는 공장 클래스를 만들어서 생성의 역할을 가지는 클래스를 만드는 것이 핵심!

또한 자식 팩토리 클래스에 구현을 하여 결정합니다.

왜 사용해야 하는지

팩토리 패턴을 사용하는 이유는 객체를 생성하는 역할을 분리하겠다는 취지가 담겨있습니다.

객체의 생성 코드를 별도의 클래스/메서드로 분리함으로써 객체 생성의 변화에 대비하는데 유용합니다.

예시

먼저 추상객체로 피자가 있습니다.

이 피자의 종류로 구현객체인 씨푸드피자, 베이컨피자, 치즈피자가 있습니다.

import java.math.BigInteger;

public abstract class Pizza {

    protected BigInteger price;
    protected PizzaType type;

    public void print() {
        System.out.println("이 피자는 "+type.getName()+"피자이며 가격은 "+price+"원 입니다.");
    }

}

class CheesePizza extends Pizza {

    protected CheesePizza() {
        this.price = new BigInteger("8000");
        this.type = PizzaType.cheese;
    }
}

class BaconPizza extends Pizza {

    protected BaconPizza() {
        this.price = new BigInteger("10000");
        this.type = PizzaType.bacon;
    }
}

class SeafoodPizza extends Pizza {

    protected SeafoodPizza() {
        this.price = new BigInteger("15000");
        this.type = PizzaType.seafood;
    }
}

 

피자를 만드는 공장은 Factory 인터페이스로 되어있습니다.

public interface PizzaFactory {
    Pizza create();
}

해당 factory를 상속받은 각각의 치즈, 베이컨, 씨푸드 공장이 있습니다.

public class BaconPizzaFactory implements PizzaFactory{

    @Override
    public Pizza create() {
        return new BaconPizza();
    }
}

public class CheesePizzaFactory implements PizzaFactory {
	
    @Override
    public Pizza create(){
       return new CheesePizza();
    }
}

public class SeafoodPizzaFactory implements PizzaFactory {

    @Override
    public Pizza create() {
        return new SeafoodPizza();
    }
}

각각의 공장은 각각의 피자를 생성하는 메서드를 가집니다.

 

이제 피자를 주문해보겠습니다.

public class PizzaClient {
    public static void main(String[] args) {
        PizzaFactory cheezePizzaFactory = new CheesePizzaFactory();
        PizzaFactory baconPizzaFactory = new BaconPizzaFactory();
        PizzaFactory seafoodPizzaFactory = new SeafoodPizzaFactory();
        Pizza cheesePizza = cheezePizzaFactory.create();
        Pizza baconPizza = baconPizzaFactory.create();
        Pizza seafoodPizza = seafoodPizzaFactory.create();

        cheesePizza.print();
        baconPizza.print();
        seafoodPizza.print();
    }
}

실행결과

이처럼 피자의 생성은 각각의 피자공장이 책임을 지니게 됨으로써 객체를 생성하는 역할을 분리하게 되었습니다.

 

해당 코드는 깃허브 레포에 있습니다!

hdcd_source_java_designpattern_gof/ch01/src/com/my/pattern/abstractfactory at master · lsm7179/hdcd_source_java_designpattern_gof

 

GitHub - lsm7179/hdcd_source_java_designpattern_gof: 자바로 보는 디자인 패턴 스터디 및 공부

자바로 보는 디자인 패턴 스터디 및 공부. Contribute to lsm7179/hdcd_source_java_designpattern_gof development by creating an account on GitHub.

github.com

 

스프링에서 예시

BeanFactory (Spring Framework 5.3.23 API)

 

BeanFactory (Spring Framework 5.3.23 API)

Determine the type of the bean with the given name. More specifically, determine the type of object that getBean(java.lang.String) would return for the given name. For a FactoryBean, return the type of object that the FactoryBean creates, as exposed by Fac

docs.spring.io

Bean을 생성하는 클래스는 BeanFactory

 

정적 팩토리 메서드

정적 팩토리 메서드는 조금 다릅니다.

정적 팩토리 메서드는 LocalDateTime.of, List.of 등

static 으로 자기 자신의 객체를 생성하는 경우를 말합니다.

추상 팩토리 메소드 패턴 vs 팩토리 메소드 패턴 차이

팩토리 메소드 패턴 (factory method) 추상 팩토리 패턴 (abstract factory) 차이

 

팩토리 메소드 패턴 (factory method) 추상 팩토리 패턴 (abstract factory) 차이

이거 은근 볼 때마다 헷갈린다. 일단 내게 깨달음을 준 stackoverflow 를 보자. The main difference between a "factory method" and an "abstract factory" is that the factory method is a single method, and..

whereami80.tistory.com

factory method pattern vs abstract factory pattern 차이 알아보기

 

factory method pattern vs abstract factory pattern 차이 알아보기

factory method pattern vs abstract factory pattern 차이 알아보기 두 패턴은 공통점이 많지만 확연히 다른 차이점이 존재합니다. 펙토리 메서드 패턴과 추상 메서드 패턴의 차이에 대하여 알아보도록.

beomseok95.tistory.com

 

감사합니다.

반응형

'프로그래밍 > 디자인패턴' 카테고리의 다른 글

자바 커맨드(Command) 패턴  (0) 2022.12.12
자바 데커레이터(Decorator) 패턴  (0) 2022.11.15
자바 전략 패턴  (0) 2022.11.03
자바 프록시 패턴  (0) 2022.11.01
자바 빌더 패턴  (0) 2022.10.30

댓글