Java/DesignPattern
팩토리 메서드 패턴
amungstudy
2024. 5. 16. 14:56
Factory method pattern (생성패턴)
객체가 생성되는 과정을 숨기고 완성된 인스턴스만 반환하는 패턴이다.
new연산자로 객체를 생성하지 않고, 객체의 생성과정을 다른 객체에 맡겨서 리턴 받아서 사용한다
이렇게 객체 생성을 대신 해주는 클래스를 Factory 라고 한다.
장점 : 코드 간 결합도를 낮출 수 있다.
예시)
public class Bus {
}
public class BeanFactory {
public Bus getBus(){
return new Bus();
}
}
Bus 객체를 만들 때, new 연산자로 생성하지 않고
BeanFactory 클래스를 통해서 객체를 사용한다.
public class BeanFactoryMain {
public static void main(String[] args) {
BeanFactory bf = new BeanFactory();
//Bus bus = new Bus();
Bus bus1 = bf.getBus();
Bus bus2 = bf.getBus();
}
}
참조 : https://www.youtube.com/watch?v=8A6ElEmMnSY