Liskov Substitution Principle (LSP)
The principle states that objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program.
Certainly! Let's demonstrate the Liskov Substitution Principle (LSP) with an example involving addition and subtraction operations in C#.
First, let's define an interface `IOperation` representing different mathematical operations:
```csharp
// Operation interface
public interface IOperation
{
int Apply(int x, int y);
}
Next, we implement two classes, `Addition` and `Subtraction`, representing 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 performs addition and subtraction operations based on the Liskov Substitution Principle:
```csharp
// Calculator class adhering to the Liskov Substitution Principle
public class Calculator
{
public int PerformOperation(IOperation operation, int x, int y)
{
return operation.Apply(x, y);
}
}
In this implementation, both `Addition` and `Subtraction` classes implement the `IOperation` interface. The `Calculator` class takes any object that implements `IOperation` and performs the operation without knowing the specific class being used, demonstrating the Liskov Substitution Principle.
Here's how you can use these classes:
```csharp
class Program
{
static void Main()
{
Calculator calculator = new Calculator();
IOperation addition = new Addition();
int result1 = calculator.PerformOperation(addition, 10, 5);
Console.WriteLine("Addition Result: " + result1); // Output: 15
IOperation subtraction = new Subtraction();
int result2 = calculator.PerformOperation(subtraction, 10, 5);
Console.WriteLine("Subtraction Result: " + result2); // Output: 5
}
}
In this example, both `Addition` and `Subtraction` classes can be substituted wherever an `IOperation` object is expected, without altering the correctness of the program, adhering to the Liskov Substitution Principle.
No comments:
Post a Comment
Comments Welcome