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

4.7 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-polymorphism-다형성 Polymorphism (다형성) 10_Wiki/Topics verified self
Polymorphism
다형성
Polymorphism in Engine Architecture
none A 0.9 applied
oop
type-system
design
architecture
2026-05-10 pending
language framework
python-cpp-rust 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)

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)

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)

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)

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)

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)

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)

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

🤖 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.

🧪 검증 / 중복

🕓 Changelog

날짜 변경
2026-05-08 Phase 1
2026-05-10 Manual cleanup — 4 forms + dispatch axes + working examples