Java/Java 기초
[Java 기초] 팩토리 메서드 패턴
메성
2019. 12. 14. 22:35
반응형
팩토리 메서드 패턴
팩토리 메서드 패턴이란,
객체를 생성하는 부분을 서브 클래스로 분리하여 처리하도록 캡슐화한 패턴을 말한다.
- 결과적으로, 객체를 만들어내는 공장을 만드는 패턴
Ex.
//1. 로봇의 인터페이스와 로봇을 구현하는 구현체를 작성 //Robot public interface Robot { public String name(String name); } //AnimalRobot public class AnimalRobot implements Robot { @Override public String name(String name) { return "Animal"; } } //HumanRobot public class HumanRobot implements Robot { @Override public String name(String name) { return "Human"; } } //2. 로봇을 생성하기 위한(팩토리 접근) Creator 생성 //RobotCreator public class RobotCreator { public Robot creator(String name) { RobotFactory robotFactory = new RobotFactory(); Robot robot = robotFactory.create(name); return robot; } } //3. 실질적으로 로봇을 생성하는 팩토리 클래스를 작성 //RobotFactory public class RobotFactory { public Robot create(String name) { Robot robot = null; if(name.equals("Human")) { robot = new HumanRobot(); } else if(name.equals("Animal")) { robot = new AnimalRobot(); } return robot; } } //4. 결과적으로, 로봇 생성하는 Creator를 활용하여 고객이 원하는 로봇 생성 //Main public class Main { public static void main(String[] args) { //Fectory Method Pattern Main RobotCreator robotCreator = new RobotCreator(); robotCreator.creator("Human"); robotCreator.creator("Animal"); } }
팩토리 메서드 패턴을 사용 안 하고, Creator를 이용해 Robot객체에 바로 접근하여 생성하게 된다면, AnimalRobot 및 HumanRobot과 마찬가지로 다른 Robot이 나타나게 된다면 Creator는 변경해야하는 현상이 발생한다.
또한, 객체 생성하는 부분의 결합도가 강하게 결합되어져 유지보수가 힘들어질 것이다.
따라서, 팩토리 메서드 패턴을 활용하여 Creator는 팩토리에만 접근하여 객체를 생성할 수 있도록 하여 결합도를 느슨하게 만드는 것이다.
이를 통해, Cretor는 다른 Robot객체가 추가되어도 코드 수정이 이루어지지 않고 로봇의 이름의 메시지만 전달해주면 Robot을 손쉽게 생성할 수 있게 된다.
반응형