简单工厂模式具体例子C#
时间: 2024-09-12 14:11:56 浏览: 82
简单工厂模式是一种创建型设计模式,它提供了一个创建对象的最佳方式,而无需暴露其内部的创建逻辑。在C#中,简单工厂的一个基本例子可以用于创建不同类型的形状对象,如矩形、圆形等。这里有一个简单的实现:
```csharp
// 定义一个基础形状接口
public interface IShape
{
void Draw();
}
// 每种具体的形状类都实现IShape接口
public class Rectangle : IShape
{
public void Draw()
{
Console.WriteLine("Drawing a rectangle.");
}
}
public class Circle : IShape
{
public void Draw()
{
Console.WriteLine("Drawing a circle.");
}
}
// 简单工厂类
public class ShapeFactory
{
// 根据传入的类型创建相应的形状实例
public static IShape CreateShape(string shapeType)
{
switch (shapeType)
{
case "Rectangle":
return new Rectangle();
case "Circle":
return new Circle();
default:
throw new ArgumentException("Invalid shape type.");
}
}
}
// 主函数示例
public static void Main()
{
var rectangle = ShapeFactory.CreateShape("Rectangle");
rectangle.Draw(); // 输出:Drawing a rectangle.
var circle = ShapeFactory.CreateShape("Circle");
circle.Draw(); // 输出:Drawing a circle.
}
```
在这个例子中,`ShapeFactory`类隐藏了如何实际创建特定形状的细节,客户端只需通过给定的类型请求需要的对象即可。这使得代码更易于维护和扩展。
阅读全文
相关推荐
















