What problem simply factory solves?
Multiple types can be instantiated and the choice is based on some simple criteria.
여러 유형을 인스턴스화할 수 있으며 선택은 몇 가지 간단한 기준을 기반으로 한다.
추상 클래스를 상속받은 여러 유형의 클래스 생성.
간단한 기준(criteria)으로 선택. -> 팩토리 클래스에서 분기 처리
추상 클래스로 여러 유형을 인스턴스화 할 수 있음.
ex)
추상 클래스 : Post
추상 클래스를 상속받은 여러 유형의 클래스 : BlogPost, NewsPost, ProductPost
팩토리 클래스 : PostFactory
Post post = PostFactory.createPost(criteria);
PostFactory에서 criteria 값에 따라 분기 처리(static method)
criteria가 "blog"면 post의 실제 클래스는 BlogPost
criteria가 "news"면 post의 실제 클래스는 NewsPost
criteria가 "product"면 post의 실제 클래스는 ProductPost
What is a Simple Factory?
Simply move the instantiation logic to a separate class and most commonly to a static method of this class.
Some do not consider simple factory to be a "design pattern", as its simply a method that encapsulates object instantiation. Nothing Complex goes on in that method.
Typically we want to do this if we have more than one option when instantiating object and a simple logic is used to choose correct class.
인스턴스화하는 로직을 별도의 클래스로 옮기고 그 클래스의 static method로 구현했다.
단순히 객체 인스턴스화를 캡슐화하는 방법이기 때문에 소수의 사람들은 Simple Factory를 "디자인 패턴"으로 보지 않는다. * factory method 패턴과 혼동하기도 한다.
일반적으로 객체를 인스턴스화 할 때 하나 이상의 옵션이 있고 맞는 클래스를 고르기 위해 간단한 로직이 사용되면 Simple Factory 패턴으로 구현한다.
Implement a Simple Factory
We start by creating a separate class for our simple factory.
Add a method which returns desired object instance.
This method is typically static and will accept some argument to decide which class to instantiate.
You can also provide additional arguments which will be used to instantiate objects.
Simple Factory를 위한 별도의 클래스를 생성하고 찾고자 하는 객체의 인스턴스를 반환하는 메서드를 추가한다.
이 메서드는 일반적으로 static이고 어떤 클래스를 인스턴스화할지 정하기 위해 인자(들)가 필요할 수 있다.
해당 메서드에서 객체를 인스턴스화하기 위해 사용될 수 있는 추가적인 인자(들)를 제공할 수 있다.
Implementation Considerations
Simple factory can be just a method in existing class. Adding a separate class however allows other parts of your code to use simple facotry more easily.
Simple factory itself doesn't need any state tracking so it's best to keep this as a static method.
매서드만으로 구현할 수 있지만 별도의 클래스를 생성해서 구현하는 것은 접근성을(보다 쉽게 사용할 수 있게) 위한 것이다.
해당 클래스의 상태를 추적할 필요가 없어 static method로 사용하는 것이 좋다.
Design Considerations
Simple factory will in turn may use other design pattern like builder to construct objects.
In case you want to specialize your simple factory in sub classes, you need factory method design pattern instead.
Simple factory는 빌더와 같은 다른 디자인 패턴을 사용하여 객체를 구성할 수 있다.
하위 클래스에서 Simple factory를 구체화하려는 경우 대신 팩토리 메소드 디자인 패턴이 필요하다.
Pitfalls
The criteria used by simple factory to decide which object to instantiate can get more convoluted/complex over time. If you find yourself in such situation then use factory method design pattern.
어떤 객체를 인스턴스화할지 정하기 위해 simple factory에서 사용하는 기준이 시간이 지날 수록 난해해지고 복잡해질 수 있다. 만약 그렇다면 팩토리 매서드 디자인 패턴을 사용하자.
'개발 > Design Pattern' 카테고리의 다른 글
Singleton (0) | 2023.03.22 |
---|---|
[Design Pattern] State Pattern (상태 패턴) (0) | 2023.01.22 |