팩토리 패턴은 객체를 생성하는 일을 추상화한 것으로, 객체 생성 과정을 캡슐화해 캡슐화된 객체를 통해 객체를 생성할 수 있게 합니다. 이를 이용해 어떤 객체가 어떤 생성자를 사용해 생성되었는지 추적할 수 있게 해주고, 객체 생성 과정을 숨길 수 있게 합니다.
Golang에서 팩토리 패턴을 적용할 수 있는 예시는 아래와 같습니다.
type Animal interface {
Speak() string
}
type Dog struct {
}
func (d *Dog) Speak() string {
return "Woof!"
}
type Cat struct {
}
func (c *Cat) Speak() string {
return "Meow!"
}
type AnimalFactory struct {
}
func (f *AnimalFactory) CreateAnimal(t string) Animal {
if t == "dog" {
return new(Dog)
} else if t == "cat" {
return new(Cat)
}
return nil
}
이 코드에서 AnimalFactory가 팩토리 패턴을 적용한 것입니다. CreateAnimal 함수를 이용해 Animal 인터페이스를 구현한 Dog 구조체나 Cat 구조체를 생성할 수 있습니다.
이를 이용해 아래와 같이 객체를 생성할 수 있습니다.
factory := AnimalFactory{}
dog := factory.CreateAnimal("dog")
cat := factory.CreateAnimal("cat")
fmt.Println(dog.Speak())
fmt.Println(cat.Speak())
위의 코드를 실행하면 다음과 같은 결과를 얻을 수 있습니다.
Woof!
Meow!
이처럼 팩토리 패턴을 적용하면 객체 생성 과정을 캡슐화해 객체를 생성하는 과정을 추상화할 수 있습니다. 그리고 객체의 종류를 추적할 수 있게 해주고 객체 생성 과정을 숨길 수 있습니다.
[광고] STEEM 개발자 커뮤니티에 참여 하시면, 다양한 혜택을 받을 수 있습니다.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Upvoted! Thank you for supporting witness @jswit.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit