[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
+225 -36
View File
@@ -2,59 +2,248 @@
id: wiki-2026-0508-factory-pattern
title: Factory Pattern
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AI-FACTORY]
aliases: [factory, factory method, abstract factory, simple factory, GoF factory]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [DesignPatterns, Factory, OOP, Abstraction]
confidence_score: 0.97
verification_status: applied
tags: [design-pattern, gof, factory, oop, creational, abstract-factory]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: TypeScript / Python / Java
applicable_to: [OOP, Plugin System, DI]
---
# [[Factory-Pattern]] (팩토리 패턴)
# Factory Pattern
## 📌 한 줄 통찰 (The Karpathy Summary)
> "객체 생성을 전담하는 대리인." 어떤 구체적인 클래스의 인스턴스를 만들지 결정하는 로직을 별도의 객체나 메서드로 분리하여, 클라이언트 코드가 생성 방식의 변화로부터 자유로워지게 하는 패턴이다.
## 한 줄
> **"매 object creation 의 의 의 encapsulate"**. GoF creational. 매 simple factory (function), 매 factory method (method), 매 abstract factory (factory of factories). 매 modern: 매 DI / DI container 의 partly 의 replace.
## 📖 구조화된 지식 (Synthesized Content)
- **Simple Factory**: 입력값에 따라 다른 자식 객체를 생성하여 리턴함.
- **Factory Method**: 상속을 통해 어떤 객체를 생성할지 서브클래스가 결정하게 함.
- **Abstract Factory**: 연관된 객체들의 '군(Family)'을 생성하기 위한 인터페이스를 제공함 (예: 다크 테마용 버튼과 입력창 세트).
- **Core Benefit**: **Decoupling**. `new` 키워드를 한곳에서 관리하므로, 나중에 구현체가 바뀌어도 사용하는 쪽 코드는 전혀 수정할 필요가 없다.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- 팩토리 패턴은 코드의 유연성을 높이지만, 단순한 객체 생성에도 팩토리를 도입하면 클래스 수가 많아지고 구조가 복잡해지는 '클래스 폭발'을 유발할 수 있다. 객체 생성 로직이 복잡하거나 타입에 따라 분기가 빈번할 때만 선택적으로 사용하는 것이 좋다.
### 매 variant
- **Simple factory**: 매 단순 function.
- **Factory method**: 매 polymorphic creation.
- **Abstract factory**: 매 family of factories.
## 🔗 지식 연결 (Graph)
- Related: [[Dependency-Injection]] , Abstract-Factory-Pattern
- Concept: Encapsulation
### 매 motivation
- 매 client 의 concrete class 의 의 know X.
- 매 creation logic 의 encapsulate.
- 매 family of related objects.
- 매 testability (mock).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 modern alternative
- **DI container** (Inversify, NestJS).
- **Builder** (complex creation).
- **Static factory method** (named).
- **Functional factory**.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Simple factory
```typescript
function createButton(theme: 'light' | 'dark'): Button {
if (theme === 'light') return new LightButton();
return new DarkButton();
}
```
## 🧪 검증 상태 (Validation)
### Factory method
```typescript
abstract class Dialog {
protected abstract createButton(): Button;
render() {
const btn = this.createButton();
btn.render();
}
}
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
class WindowsDialog extends Dialog {
protected createButton(): Button {
return new WindowsButton();
}
}
## 🧬 중복 검사 (Duplicate Check)
class MacDialog extends Dialog {
protected createButton(): Button {
return new MacButton();
}
}
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Abstract factory
```typescript
interface UIFactory {
createButton(): Button;
createCheckbox(): Checkbox;
}
## 🕓 변경 이력 (Changelog)
class WindowsFactory implements UIFactory {
createButton() { return new WindowsButton(); }
createCheckbox() { return new WindowsCheckbox(); }
}
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
class MacFactory implements UIFactory {
createButton() { return new MacButton(); }
createCheckbox() { return new MacCheckbox(); }
}
function getFactory(): UIFactory {
return process.platform === 'darwin' ? new MacFactory() : new WindowsFactory();
}
```
### Static factory method (Effective Java)
```typescript
class User {
private constructor(public id: string, public role: string) {}
static guest() { return new User('guest', 'guest'); }
static admin(id: string) { return new User(id, 'admin'); }
static fromJSON(json: any) { return new User(json.id, json.role); }
}
```
### Functional (Python)
```python
from typing import Callable
def make_logger(level: str) -> Callable:
if level == 'debug':
return lambda msg: print(f'[DEBUG] {msg}')
if level == 'error':
return lambda msg: sys.stderr.write(f'[ERROR] {msg}\n')
return lambda msg: print(msg)
```
### Registry-based factory
```python
class ShapeRegistry:
_registry: dict = {}
@classmethod
def register(cls, name: str):
def decorator(klass):
cls._registry[name] = klass
return klass
return decorator
@classmethod
def create(cls, name: str, *args, **kwargs):
return cls._registry[name](*args, **kwargs)
@ShapeRegistry.register('circle')
class Circle:
def __init__(self, r): self.r = r
shape = ShapeRegistry.create('circle', 5)
```
### DI container alternative (NestJS)
```typescript
@Injectable()
class UserService {
constructor(
@Inject('UserRepo') private repo: UserRepo,
private logger: Logger,
) {}
}
@Module({
providers: [
UserService,
Logger,
{ provide: 'UserRepo', useClass: PostgresUserRepo },
],
})
class AppModule {}
```
### Plugin / strategy factory
```python
PARSERS = {
'json': JSONParser,
'yaml': YAMLParser,
'toml': TOMLParser,
}
def parse(content, format):
return PARSERS[format]().parse(content)
```
### Conditional with extensibility
```python
class ModelFactory:
def __init__(self):
self.providers = {}
def register(self, name, provider_cls):
self.providers[name] = provider_cls
def create(self, name, **config):
if name not in self.providers:
raise ValueError(f'Unknown provider: {name}')
return self.providers[name](**config)
factory = ModelFactory()
factory.register('openai', OpenAIProvider)
factory.register('anthropic', AnthropicProvider)
```
### Async factory
```python
class DBConnectionFactory:
@classmethod
async def create(cls, url):
conn = AsyncConnection(url)
await conn.connect()
return conn
db = await DBConnectionFactory.create('postgres://...')
```
## 매 결정 기준
| 상황 | Pattern |
|---|---|
| Simple variant | Simple factory function |
| Polymorphic creation | Factory method |
| Family of objects | Abstract factory |
| Many params | Builder |
| Plugin system | Registry |
| DI heavy | DI container |
| Functional | Closure factory |
**기본값**: 매 simple = 매 plain function. 매 plugin = registry. 매 DI = container. 매 family = abstract factory.
## 🔗 Graph
- 부모: [[Design-Pattern]] · [[GoF]]
- 변형: [[Builder]] · [[Singleton]] · [[Prototype]]
- 응용: [[Plugin-System]] · [[Dependency-Injection]]
- Adjacent: [[Strategy-Pattern]] · [[Encapsulation-and-Information-Hiding]]
## 🤖 LLM 활용
**언제**: 매 plugin / multiple impl. 매 testability. 매 family of objects.
**언제 X**: 매 single concrete (just `new`).
## ❌ 안티패턴
- **Factory for factory's sake**: 매 single impl.
- **God factory**: 매 too many responsibilities.
- **Hidden global state**: 매 testability lose.
- **Switch explosion**: 매 registry 의 prefer.
- **Reinventing DI**: 매 use container.
## 🧪 검증 / 중복
- Verified (GoF Design Patterns, Effective Java).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-04-20 | Auto-reinforced |
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — variants + 매 simple / method / abstract / registry / DI code |