0

# 開閉原則 The Open/Closed Principle (OCP)

### 閉 : 封閉修改

``````    //產品:三角形
public class Triangle
{
public static void Show()
{
Console.WriteLine(\$"這是一個 Triangle ");
}
}
//產品:方形
public class Square
{
public static void Show()
{
Console.WriteLine(\$"這是一個 Square ");
}
}
//實作方法
public class Display
{
public void ShowTheSharp(string sharp)
{
if (sharp == "Square")
{
Square square = new Square();
square.Show();
}
else if (sharp == "Triangle")
{
Triangle triangle = new Triangle();
triangle.Show();
}
}
}
``````

``````    //新增 產品:圓形
public class Circle
{
public static void Show()
{
Console.WriteLine(\$"這是一個 Circle ");
}
}
//實作方法
public class Display
{
public void ShowTheSharp(string sharp)
{

if (sharp == "Square")
{
Square square = new Square();
square.Show();
}
else if (sharp == "Triangle")
{
Triangle triangle = new Triangle();
triangle.Show();
}
//////新增判斷//////
else if (sharp == "Circle")
{
Circle circle = new Circle();
circle.Show();
}
}
}
``````

#### 抽象化是開閉原則的關鍵而依賴注入則是實現開閉原則的方法。

`````` public abstract class Sharp
{
public virtual void Show() { }
}

public class Triangle : Sharp
{
public override void Show()
{
Console.WriteLine(\$"這是一個 Triangle ");
}
}
public class Square : Sharp
{
public override void Show()
{
Console.WriteLine(\$"這是一個 Square ");
}
}
public class Circle : Sharp
{
public override void Show()
{
Console.WriteLine(\$"這是一個 Circle ");
}
}

public class Display
{
public Sharp sharp;
//依賴注入
public void SetSharp(Sharp _sharp)
{
this.sharp = _sharp;
}
public void ShowTheSharp()
{
this.sharp.Show();
//if (sharp == "Square")
//{
//    Square square = new Square();
//    square.Show();
//}
//else if (sharp == "Triangle")
//{
//    Triangle triangle = new Triangle();
//    triangle.Show();
//}
//else if (sharp == "Circle")
//{
//    Circle circle = new Circle();
//    circle.Show();
//}
}
}
``````