PHpullh
학습 라이브러리/Go/SOLID 원칙 적용

GO · 구조체/인터페이스

SOLID 원칙 적용

Go에서 SOLID 원칙을 적용합니다. 작은 인터페이스와 합성이 Go 스타일의 SOLID입니다.

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

핵심 설명

Go에서 SOLID 원칙을 적용합니다. 작은 인터페이스와 합성이 Go 스타일의 SOLID입니다.

Go code

package main

import "fmt"

// S — 단일 책임: 각 타입이 하나의 역할
type Validator struct{}
func (v Validator) Validate(email string) bool { return len(email) > 3 }

type Formatter struct{}
func (f Formatter) Format(name string) string { return "Mr./Ms. " + name }

// O — 개방/폐쇄: 인터페이스로 확장
type Notifier interface { Notify(msg string) }

type EmailNotifier struct{}
func (e EmailNotifier) Notify(msg string) { fmt.Println("이메일:", msg) }

type SMSNotifier struct{}
func (s SMSNotifier) Notify(msg string) { fmt.Println("SMS:", msg) }

// I — 인터페이스 분리: 작은 인터페이스
type Reader interface { Read() string }
type Writer interface { Write(s string) }

// D — 의존성 역전: 추상에 의존
type App struct {
	notifiers []Notifier
}

func (a *App) Alert(msg string) {
	for _, n := range a.notifiers {
		n.Notify(msg) // 인터페이스에 의존
	}
}

func main() {
	app := &App{notifiers: []Notifier{EmailNotifier{}, SMSNotifier{}}}
	app.Alert("서버 점검 안내")
}

학습 팁

Go의 암시적 인터페이스 구현은 OCP와 DIP를 자연스럽게 지원합니다. "Accept interfaces, return structs" 원칙을 따르세요.

주의할 점

Java처럼 큰 인터페이스를 만들면 ISP를 위반합니다. Go에서는 1-2개 메서드의 작은 인터페이스가 최선입니다.

자주 묻는 질문

SOLID 원칙 적용란 무엇인가요?

Go에서 SOLID 원칙을 적용합니다. 작은 인터페이스와 합성이 Go 스타일의 SOLID입니다.

SOLID 원칙 적용 학습 시 주의할 점은 무엇인가요?

Java처럼 큰 인터페이스를 만들면 ISP를 위반합니다. Go에서는 1-2개 메서드의 작은 인터페이스가 최선입니다.