Open/Closed Principle (OCP)
It states that software entities (such as classes, modules, and functions) should be open for extension but closed for modification. In other words, the behavior of a module can be extended without altering its source code.
Certainly! Let's extend the example to demonstrate the Open/Closed Principle (OCP) using an addition and subtraction scenario in C#.
First, we define an interface `IOperation` that represents different mathematical operations:
```csharp
// Operation interface
public interface IOperation
{
int Apply(int x, int y);
}
Next, we implement two classes, `Addition` and `Subtraction`, that represent the addition and subtraction operations respectively:
```csharp
// Addition class implementing IOperation interface
public class Addition : IOperation
{
public int Apply(int x, int y)
{
return x + y;
}
}
// Subtraction class implementing IOperation interface
public class Subtraction : IOperation
{
public int Apply(int x, int y)
{
return x - y;
}
}
Now, let's create a calculator class `Calculator` that can perform addition and subtraction operations without modifying its existing code:
```csharp
// Calculator class adhering to the Open/Closed Principle
public class Calculator
{
public int PerformOperation(IOperation operation, int x, int y)
{
return operation.Apply(x, y);
}
}
In this example, the `Calculator` class is closed for modification because it doesn't need to be changed when new operations (like multiplication, division, etc.) are added. We can extend the functionality of the calculator by creating new classes that implement the `IOperation` interface.
Here's how you might use these classes:
```csharp
class Program
{
static void Main()
{
Calculator calculator = new Calculator();
// Perform addition operation
IOperation addition = new Addition();
int result1 = calculator.PerformOperation(addition, 10, 5);
Console.WriteLine("Addition Result: " + result1); // Output: 15
// Perform subtraction operation
IOperation subtraction = new Subtraction();
int result2 = calculator.PerformOperation(subtraction, 10, 5);
Console.WriteLine("Subtraction Result: " + result2); // Output: 5
}
}
In this way, the `Calculator` class is open for extension. You can add new operations by creating new classes that implement the `IOperation` interface without modifying the existing `Calculator` class, thereby following the Open/Closed Principle.