OCP Structure: Abstraction and Concrete Implementations
Generic Structure
The Open-Closed Principle relies on defining stable abstractions that capture invariant behavior, while allowing concrete implementations to vary. Clients depend on the abstraction, not on specific implementations.
Key Participants
1. Abstraction Layer (PaymentMethod): Defines the contract that all implementations must follow. This is the "closed" part - the interface signature should not change frequently.
2. Concrete Implementations (CreditCard, PayPal, Cryptocurrency): These are the "extension" points. New payment methods can be added by creating new classes that implement the interface, without modifying existing code.
3. Client (PaymentProcessor): Depends only on the abstraction. The client's code remains unchanged when new implementations are added. It uses polymorphism to invoke the correct implementation at runtime.
Relationship Types
The triangle symbol (▲) represents inheritance/realization. Concrete classes implement or extend the abstract type. The PaymentProcessor has a composition relationship (◆) with PaymentMethod, holding a reference to work with any implementation.
Extension Without Modification
To add Cryptocurrency payment support: First, create a new class that implements PaymentMethod. Second, implement the processPayment() method with cryptocurrency-specific logic. Third, pass the new implementation to PaymentProcessor. No existing classes (CreditCard, PayPal, PaymentProcessor) are modified.