본문 바로가기

Study/Design Pattern

[Pattern] Factory Method Pattern

Factory Method Pattern

  • 부모 클래스에 알려지지 않은 구체 클래스를 생성하는 패턴
  • 자식 클래스가 어떤 객체를 생성할지를 결정하도록 하는 패턴이기도 함.
  • 즉, 객체를 만들어내느 부분을 서브 클래스에 위임하는 패턴이다.
  • 부모 클래스 코드에 구체 클래스 이름을 감추기 위한 방법으로도 사용한다.

구조

아래처럼 로봇 객체를 만드는 추상클래스가 있다고 가정했을 때,

Robot (추상 클래스)
- SuperRobot
- PowerRobot

RobotFactory (추상 클래스)
- SuperRobotFactory
ModifiedSuperRobotFactory

Robot

각각의 클래스는 아래와 같은 구조라고 하면

public abstract class Robot{
    public String getName();
}

public class SuperRobot extends Robot{
    @Override
    public String getName(){
        return "SuperRobot";
    }
}

public class PowerRobot extends Robot{
    @Override
    public String getName(){
        return "PowerRobot";
    }
}

Robot Factory

// 기본 팩토리 클래스
public abstract class rRobotFactory{
    abstract Robot createRobot(String name);
}

// 기본 팩토리 클래스를 상속 받아 실제 로직을 구현한 팩토리
public class SuperRobotFactory extends RobotFactory{

    @Override
    Robot createRobot(String name){
        switch(name){
            case "super": return new SuperRobot();
            case "power": return new PowerRobot();    
        }
        return null;
    }
}

// 로봇 클래스의 이름을 인자로 받아 직접 인스턴스를 만들어내는 팩토리
public class ModifiedSuperRobotFactory extends RobotFactory{

    @Override
    Robot createRobot(String name){
        try{
            Class<?> cls = Class.forName(name);
            Object obj = cls.newInstance();
            return(Robot)obj;
        } catch (Exception e){
            return null;
        }
    }

}

Test Code

public class FactoryMain{
    public static void main(String[] args){

        RobotFactory rf = new SuperRobotFactory();
        // 파라미터에 따라 생성되는 클래스가 다르다.
        Robot r1 = rf.createRobot("super");
        Robot r2 = rf.createRobot("power");

        RobotFactory mrf = new ModifiedSuperRobotFactory();

        // 클래스의 정확한 이름을 넣어주어야 한다.
        Robot r3 = rf.createRobot("pattern.factory.SuperRobot");
        Robot r4 = rf.createRobot("pattern.factory.PowerRobot");
    }
}

정리

객체 생성을 Factory 클래스에 위임하여 어떤 객체가 생성되었는지 신경쓰지 않고 반환된 객체를 사용만 하면 된다.

새로운 로봇이 추가되고 새로운 팩토리가 추가 된다 하더라도, 메인 프로그램에서 변경할 코드는 최소화 된다.

팩토리 메소드 패턴을 사용하는 이유는 클래스간의 결합도를 낮추기 위한 것이다.

결합도란 간단하게 클래스의 변경점이 생겼을 때 다른 클래스에 얼마나 영향을 주는가를 말한다.

팩토리 메소드 패턴을 사용하면 서브 클래스에 객체 생성을 위임함으로써 보다 효율적인 코드 제어를 할 수 있고 의존성을 제거하여 결과적으로 결합도를 낮출 수 있다.

'Study > Design Pattern' 카테고리의 다른 글

[Pattern] Template Method Pattern  (0) 2022.01.15
[Pattern] Singleton Pattern  (0) 2022.01.15
[Pattern] Adapter Pattern  (0) 2022.01.15
[Pattern] 디자인 패턴 개요  (0) 2022.01.15
[WEB] MVC패턴  (0) 2021.10.14