SOLID Principles • Open-Closed PrincipleMedium⏱️ ~2 min

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.

«interface»
PaymentMethod
+ processPayment(amount): Result
▲
CreditCard
+ processPayment()
PayPal
+ processPayment()
Cryptocurrency
+ processPayment()
PaymentProcessor
- method: PaymentMethod
+ checkout(amount): void

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.

Interview Tip: When drawing diagrams, clearly distinguish between interfaces (dashed borders) and concrete classes (solid borders). This shows you understand abstraction layers.

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.

💡 Key Takeaways
✓Abstraction layer defines stable contracts that implementations follow
✓Concrete classes extend functionality without modifying the abstraction
✓Client code depends on abstractions, not concrete implementations
✓New functionality is added by creating new classes, not editing existing ones
✓Use interfaces (dashed) for abstractions and solid borders for concrete classes
📌 Interview Tips
1PaymentMethod interface with multiple payment type implementations
2NotificationService with Email, SMS, and Push implementations
3Shape hierarchy with Circle, Rectangle, Triangle extending Shape
← Back to Open-Closed Principle Overview
OCP Structure: Abstraction and Concrete Implementations | Open-Closed Principle - System Overflow