C# 设计模式(一) 单例模式、工厂模式、观察者模式、策略模式
发布人:shili8
发布时间:2024-03-20 09:38
阅读次数:109
在C#中,设计模式是一种解决特定问题的通用方法。设计模式可以帮助我们更好地组织和管理代码,提高代码的可维护性和可扩展性。在本文中,我们将介绍C#中常用的四种设计模式:单例模式、工厂模式、观察者模式和策略模式,并提供相应的代码示例和注释。
1. 单例模式(Singleton Pattern)
单例模式是一种创建型设计模式,它确保一个类只有一个实例,并提供一个全局访问点。在C#中,可以通过私有构造函数和静态变量来实现单例模式。
csharppublic class Singleton{
private static Singleton instance;
private Singleton() { }
public static Singleton Instance {
get {
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
在上面的代码中,Singleton类只有一个私有构造函数,通过Instance属性可以获取Singleton类的唯一实例。
2. 工厂模式(Factory Pattern)
工厂模式是一种创建型设计模式,它定义一个接口用于创建对象,但让子类决定实例化哪个类。在C#中,可以通过接口和工厂类来实现工厂模式。
csharppublic interface IShape{
void Draw();
}
public class Circle : IShape{
public void Draw()
{
Console.WriteLine("Drawing a circle");
}
}
public class Rectangle : IShape{
public void Draw()
{
Console.WriteLine("Drawing a rectangle");
}
}
public class ShapeFactory{
public IShape GetShape(string shapeType)
{
if (shapeType == "Circle")
{
return new Circle();
}
else if (shapeType == "Rectangle")
{
return new Rectangle();
}
return null;
}
}
在上面的代码中,IShape接口定义了一个Draw方法,Circle和Rectangle类实现了IShape接口。ShapeFactory类根据传入的shapeType参数来创建不同的形状对象。
3. 观察者模式(Observer Pattern)
观察者模式是一种行为设计模式,它定义了一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会收到通知并自动更新。在C#中,可以通过事件和委托来实现观察者模式。
csharppublic class Subject{
public event EventHandler StateChanged;
private string state;
public string State {
get { return state; }
set {
state = value;
OnStateChanged();
}
}
protected virtual void OnStateChanged()
{
StateChanged?.Invoke(this, EventArgs.Empty);
}
}
public class Observer{
public Observer(Subject subject)
{
subject.StateChanged += (sender, e) =>
{
Console.WriteLine("Subject state changed: " + subject.State);
};
}
}
在上面的代码中,Subject类定义了一个StateChanged事件,Observer类订阅了Subject的StateChanged事件,并在事件触发时输出Subject的状态。
4. 策略模式(Strategy Pattern)
策略模式是一种行为设计模式,它定义了一系列算法,将每个算法封装起来,并使它们可以互相替换。在C#中,可以通过接口和委托来实现策略模式。
csharppublic interface IStrategy{
void Execute();
}
public class ConcreteStrategyA : IStrategy{
public void Execute()
{
Console.WriteLine("Executing strategy A");
}
}
public class ConcreteStrategyB : IStrategy{
public void Execute()
{
Console.WriteLine("Executing strategy B");
}
}
public class Context{
private IStrategy strategy;
public Context(IStrategy strategy)
{
this.strategy = strategy;
}
public void ExecuteStrategy()
{
strategy.Execute();
}
}
在上面的代码中,IStrategy接口定义了一个Execute方法,ConcreteStrategyA和ConcreteStrategyB类实现了IStrategy接口。Context类接收一个IStrategy对象,并在ExecuteStrategy方法中执行该策略。
总结设计模式是一种通用的解决问题的方法,可以帮助我们更好地组织和管理代码。在C#中,单例模式、工厂模式、观察者模式和策略模式是常用的设计模式,通过合适的场景选择合适的设计模式可以提高代码的可维护性和可扩展性。希望本文对你有所帮助,谢谢阅读!

