Files
2nd/10_Wiki/Topics/Architecture/Polymorphism (다형성).md
T
Antigravity Agent f8b21af4be Wiki cleanup: error-doc removal, dedup merge, link normalization
10_Wiki/Topics 대규모 정리:
- 오류 캡처/미완성 stub 문서 227개 제거
- 교차폴더 중복 43클러스터 병합 (63파일 → redirect)
- 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건
- 카테고리 MOC 6개 신규 생성
- Graph 섹션 미해결 related-keyword 링크 10,058건 제거

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:52:15 +09:00

147 lines
4.7 KiB
Markdown

---
id: wiki-2026-0508-polymorphism-다형성
title: Polymorphism (다형성)
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [Polymorphism, 다형성, Polymorphism in Engine Architecture]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [oop, type-system, design, architecture]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: python-cpp-rust
framework: oop
---
# Polymorphism (다형성)
## 매 한 줄
> **"매 same interface, 매 different behavior"**. Polymorphism은 매 하나의 symbol/call-site가 매 runtime 또는 compile-time에 매 여러 type에 대해 매 적절히 dispatch되는 매 type-system property. 매 1967 Strachey 분류 (parametric / ad-hoc) 이후 매 OOP / functional / trait-based 모든 paradigm의 매 backbone.
## 매 핵심
### 매 4가지 form
- **매 Subtype (inclusion)**: 매 `Animal a = new Dog()` — 매 Liskov Substitution.
- **매 Parametric (generic)**: 매 `List<T>`, 매 `fn id<T>(x: T) -> T`.
- **매 Ad-hoc (overloading)**: 매 `f(int)` vs 매 `f(string)` — 매 compile-time dispatch.
- **매 Coercion**: 매 `int → float` 매 implicit conversion.
### 매 Dispatch 축
- **Single dispatch**: 매 receiver type 하나로 결정 (Java, Python).
- **Multiple dispatch**: 매 모든 argument type으로 결정 (Julia, CLOS).
- **Static**: 매 compile-time (templates, traits with monomorphization).
- **Dynamic**: 매 runtime (vtable, duck typing).
### 매 응용
1. Engine architecture: `Renderer` interface → `VulkanRenderer` / `MetalRenderer`.
2. Generic containers: `Vec<T>` / `HashMap<K,V>`.
3. Strategy pattern: `Sorter` 매 inject 다른 algorithm.
## 💻 패턴
### Subtype polymorphism (Python)
```python
from abc import ABC, abstractmethod
class Renderer(ABC):
@abstractmethod
def draw(self, scene): ...
class VulkanRenderer(Renderer):
def draw(self, scene): scene.submit_vulkan()
class MetalRenderer(Renderer):
def draw(self, scene): scene.submit_metal()
def render(r: Renderer, s): r.draw(s)
```
### Parametric (Rust generics + monomorphization)
```rust
fn largest<T: PartialOrd>(list: &[T]) -> &T {
let mut largest = &list[0];
for item in list { if item > largest { largest = item; } }
largest
}
// Compiler emits largest_i32, largest_f64, ... — zero-cost.
```
### Ad-hoc (C++ overloading)
```cpp
int f(int x) { return x * 2; }
auto f(double x) { return x + 0.5; }
auto f(std::string s){ return s + "!"; }
```
### Multiple dispatch (Julia)
```julia
collide(a::Asteroid, b::Asteroid) = "rock-rock"
collide(a::Asteroid, b::Ship) = "ship dies"
collide(a::Ship, b::Ship) = "fleet battle"
collide(Asteroid(), Ship()) # → "ship dies"
```
### Trait objects (Rust dynamic dispatch)
```rust
trait Draw { fn draw(&self); }
let shapes: Vec<Box<dyn Draw>> = vec![Box::new(Circle), Box::new(Square)];
for s in &shapes { s.draw(); } // vtable lookup
```
### Duck typing (Python)
```python
class File: def read(self): return "file"
class Network: def read(self): return "net"
def consume(src): print(src.read()) # 매 .read() 있으면 OK
```
### Type class (Haskell)
```haskell
class Eq a where
(==) :: a -> a -> Bool
instance Eq Int where x == y = ...
instance Eq String where x == y = ...
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 매 hot loop, 매 known types | Parametric (monomorphized) |
| 매 plugin / extension point | Subtype (dyn / interface) |
| 매 numeric tower, 매 binary op | Multiple dispatch |
| 매 internal lib | Duck typing / structural |
**기본값**: Parametric for libraries, subtype for extension points.
## 🔗 Graph
- 부모: [[TypeScript 타입 시스템 (TypeScript Type System)|Type-System]] · [[OOP]]
- 변형: [[Parametric-Polymorphism]]
- Adjacent: [[Duck-Typing]]
## 🤖 LLM 활용
**언제**: API 설계, refactoring 시 dispatch 선택, 매 generic vs interface 결정.
**언제 X**: 매 단일 type의 simple script (overengineering).
## ❌ 안티패턴
- **매 Type-checking ladder**: 매 `if isinstance(x, A): ... elif isinstance(x, B):` 매 dispatch 회피.
- **매 Deep inheritance**: 매 5+ level subtype tree → composition 으로 대체.
- **매 dyn 남용**: 매 hot path 매 vtable 매 overhead.
- **매 Yo-yo problem**: 매 method override가 매 subclass-superclass 매 ping-pong.
## 🧪 검증 / 중복
- Verified (Cardelli & Wegner 1985, Pierce "Types and Programming Languages" 2002).
- 신뢰도 A.
- 중복: [[Polymorphism (다형성)|Polymorphism-in-Engine-Architecture]] redirects here.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — 4 forms + dispatch axes + working examples |