PHpullh
학습 라이브러리/Go/팩토리 패턴

GO · 구조체/인터페이스

팩토리 패턴

생성 로직을 캡슐화하는 팩토리 패턴. 인터페이스를 반환하여 구현체를 숨깁니다.

구조체/인터페이스고급factorypatterninterfaceencapsulation

핵심 설명

생성 로직을 캡슐화하는 팩토리 패턴. 인터페이스를 반환하여 구현체를 숨깁니다.

Go code

package main

import "fmt"

type Database interface {
	Connect() string
	Query(sql string) string
}

type postgres struct{ dsn string }
func (p *postgres) Connect() string { return "PostgreSQL 연결: " + p.dsn }
func (p *postgres) Query(sql string) string { return "PG: " + sql }

type sqlite struct{ path string }
func (s *sqlite) Connect() string { return "SQLite 열기: " + s.path }
func (s *sqlite) Query(sql string) string { return "SQLite: " + sql }

// 팩토리 함수
func NewDatabase(driver, source string) (Database, error) {
	switch driver {
	case "postgres":
		return &postgres{dsn: source}, nil
	case "sqlite":
		return &sqlite{path: source}, nil
	default:
		return nil, fmt.Errorf("미지원 드라이버: %s", driver)
	}
}

func main() {
	db, err := NewDatabase("postgres", "host=localhost")
	if err != nil { panic(err) }
	fmt.Println(db.Connect())
	fmt.Println(db.Query("SELECT 1"))
}

학습 팁

팩토리 함수는 인터페이스를 반환하고 구조체를 비공개(소문자)로 유지하여 구현 세부사항을 숨기세요.

주의할 점

팩토리에서 구체적 타입을 반환하면 소비자가 구현에 의존하게 됩니다. 항상 인터페이스를 반환하세요.

자주 묻는 질문

팩토리 패턴란 무엇인가요?

생성 로직을 캡슐화하는 팩토리 패턴. 인터페이스를 반환하여 구현체를 숨깁니다.

팩토리 패턴 학습 시 주의할 점은 무엇인가요?

팩토리에서 구체적 타입을 반환하면 소비자가 구현에 의존하게 됩니다. 항상 인터페이스를 반환하세요.

Continue Learning

Go 학습을 이어가세요

총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.