본문 바로가기

CS

[GoF] 2. Factory

Factory

Singleton과 같이 객체 생성관련된 디자인 패턴으로서 다음과 같은특징을 가진다.

  • 생성자를 추상화
  • 어떤 인스턴스를 만들 지는 생성자가 본인이 아닌 호출한 객체 측에서 판단한다.
  • Open-closed 준수
    • 만약 새로운 객체를 생성하는 로직을 추가할 때 기존의 코드를 건드리지 않고 확장이 가능하다.

interface를 통한 구현

type Electronic interface {
	Execute()
	Stop()
}
// phone
type phone struct {
	Number string
} 		

func (p phone) Execute() {
	fmt.Println("Call", p.Number)
}
func (p phone) Stop() {
	fmt.Println("Called", p.Number)
}
// computer
type computer struct {
	Program string
}

func (c computer) Execute() {
	fmt.Println("Execute", c.Program)
}
func (c computer) Stop() {
	fmt.Println("Exit", c.Program)
}

func Factory(model string, value string) (Electronic, error) {
	switch model {
	case "phone":
		return phone{Number: value}, nil
	case "computer":
		return computer{Program: value}, nil
	default:
		return phone{}, errors.New("존재하지 않는 모델")
	}
}

func TestFactory(t *testing.T) {
	phone, err := Factory("phone", "010-1234-5678")
	assert.Nil(t, err)
	phone.Execute()
	phone.Stop()

	computer, err := Factory("computer", "go version")
	assert.Nil(t, err)
	computer.Execute()
	computer.Stop()
}

같은 Factory로 객체를 생성하였지만 파라미터를 달라서 서로 다른 객체가 생성됨을 알 수 있다.

golang의 인터페이스는 duck type이므로 Factory를 호출한 클라이언트는 어떤 객체인지 신경쓰지 않고 함수를 실행할 수 있다.

=== RUN   TestFactory
Call 010-1234-5678
Called 010-1234-5678
Execute go version
Exit go version
--- PASS: TestFactory (0.00s)

'CS' 카테고리의 다른 글

[자료구조] 해시맵  (0) 2022.07.13
[자료구조]BST, AVL트리  (0) 2022.07.06
[자료구조] 트리 개론  (0) 2022.07.04
[Web]CORS  (1) 2022.06.20
[GoF] Singleton  (0) 2022.03.21