Foundations of Design Patterns: Core Concepts and Object-Oriented Prerequisites
Having established the foundational OOP concepts that underpin all design patterns, we now turn to the SOLID principles—a set of five object-oriented design guidelines first coined by Robert C. Martin (often referred to as “Uncle Bob”) in the early 2000s, which formalize the implicit best practices that the Gang of Four patterns implicitly rely on. While the GoF book did not explicitly reference SOLID (as the acronym was formalized years after the 1994 publication), every well-implemented design pattern adheres to at least one, and often multiple, of these principles. Let us examine each principle in detail, with concrete code examples to illustrate both the anti-pattern of violating the principle and the compliant implementation, using our ongoing notification system use case as a consistent reference.
---
Deep Dive into SOLID Principles with Practical Examples
Each SOLID principle addresses a specific class of design problems that emerge as codebases grow in size and complexity. For each principle, we will first define its core intent, show a common anti-pattern with a real-world notification system example, then demonstrate the compliant implementation with measurable benefits.
1. Single Responsibility Principle (SRP)
> *“A class should have only one reason to change.”* — Robert C. Martin[^1]
The SRP is the most foundational of the five principles: every module, class, or function should own exactly one responsibility, meaning it should only be modified when the requirements for that single responsibility change. Violations of SRP are the most common source of technical debt in early-stage codebases, as teams often cram multiple unrelated features into a single class to ship fast.
Anti-Pattern Example
Consider the initial implementation of our notification system, built to support only email and SMS notifications in its first release: ```python
反例:违反SRP的NotificationService类
class NotificationService: def send_notification(self, recipient: Dict, channel: str, content: str) -> Dict:
职责1:收件人格式验证
if channel == "email" and "@" not in recipient["email