设计模式通常通过重构而产生,而不是事先设计的——随着代码的增长和需求变得清晰,向模式重构改进了设计。这反映了一个原则:仅在实际需要时应用模式,而不是投机地应用。
模式通过重构而产生
text
Rather than designing patterns in UPFRONT (often premature/speculative), patterns often
emerge as you REFACTOR existing code:
→ start SIMPLE → as needs become clear (real complexity, real duplication, real change
points), REFACTOR toward a pattern that addresses them
→ "refactor TO a pattern" when the code would genuinely benefit
→ patterns as a destination of refactoring, not a starting blueprint
重构到模式的示例
text
→ A growing if/else or switch on "type" → refactor to STRATEGY or polymorphism
→ Duplicated object creation logic → extract a FACTORY
→ A class doing too much (God object) → split responsibilities (toward SRP; extract classes)
→ Hardcoded dependencies (hard to test) → introduce DEPENDENCY INJECTION
→ Complex subsystem usage scattered around → introduce a FACADE
→ Adding behavior via subclass explosion → refactor to DECORATOR (composition)
