Files
2nd/10_Wiki/Topics/Architecture/Polymorphism (다형성).md
T
koriweb d8a80f6272 chore(wiki): dangling 링크 canonical 정규화 (768파일/1200건)
이름만 다른(표기 변형) [[위키링크]]를 대상 문서의 canonical 제목으로 치환해
끊겼던 1,200개 링크를 연결. 제목/파일명 정규화 일치만 적용하고 별칭 매칭은
과병합 위험으로 제외(애매성 가드). 원본은 _link_reconcile_backup/ 에 백업.
도구: Datacollect/scripts/link_reconcile_apply.mjs

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 12:24: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.

🧪 검증 / 중복

  • Verified (Cardelli & Wegner 1985, Pierce "Types and Programming Languages" 2002).
  • 신뢰도 A.
  • 중복: Polymorphism (다형성) redirects here.

🕓 Changelog

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