在设计软件时,选择合适的设计模式可以帮助我们写出更加模块化、可重用、可扩展和易于维护的代码。C#作为一门流行的编程语言,广泛应用于各种软件开发中,而设计模式在C#中的应用尤为广泛。本文将从零开始,带你轻松掌握C#中的经典设计模式,并通过实例解析,让你在实际项目中能够灵活运用。
一、什么是设计模式?
设计模式是一套被反复使用、多数人知晓、经过分类编目的、代码设计经验的总结。使用设计模式的目的不是创造一个全新的东西,而是把已经经过实践检验的、成熟的、可重用的解决方案描述下来,供大家使用。
二、C#中的经典设计模式
1. 单例模式(Singleton)
单例模式确保一个类只有一个实例,并提供一个全局访问点。
示例代码:
public class Singleton
{
private static Singleton instance;
private Singleton()
{
}
public static Singleton GetInstance()
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
2. 工厂模式(Factory Method)
工厂模式定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
示例代码:
public abstract class Product
{
public abstract void Use();
}
public class ConcreteProductA : Product
{
public override void Use()
{
Console.WriteLine("使用产品A");
}
}
public class ConcreteProductB : Product
{
public override void Use()
{
Console.WriteLine("使用产品B");
}
}
public class Factory
{
public static Product CreateProduct(string type)
{
if (type == "A")
{
return new ConcreteProductA();
}
else if (type == "B")
{
return new ConcreteProductB();
}
else
{
throw new ArgumentException("未知的产品类型");
}
}
}
3. 建造者模式(Builder)
建造者模式将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
示例代码:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Job { get; set; }
}
public class PersonBuilder
{
private string name;
private int age;
private string job;
public PersonBuilder SetName(string name)
{
this.name = name;
return this;
}
public PersonBuilder SetAge(int age)
{
this.age = age;
return this;
}
public PersonBuilder SetJob(string job)
{
this.job = job;
return this;
}
public Person Build()
{
return new Person { Name = name, Age = age, Job = job };
}
}
4. 适配器模式(Adapter)
适配器模式将一个类的接口转换成客户期望的另一个接口,适配器让原本接口不兼容的类可以合作无间。
示例代码:
public interface ITarget
{
void Request();
}
public class Adaptee
{
public void SpecificRequest()
{
Console.WriteLine("特定请求");
}
}
public class Adapter : ITarget
{
private Adaptee adaptee;
public Adapter(Adaptee adaptee)
{
this.adaptee = adaptee;
}
public void Request()
{
adaptee.SpecificRequest();
}
}
5. 装饰者模式(Decorator)
装饰者模式动态地给一个对象添加一些额外的职责,就增加功能来说,装饰者模式比生成子类更为灵活。
示例代码:
public abstract class Component
{
public abstract void Operation();
}
public class ConcreteComponent : Component
{
public override void Operation()
{
Console.WriteLine("执行基本操作");
}
}
public class Decorator : Component
{
private Component component;
public Decorator(Component component)
{
this.component = component;
}
public override void Operation()
{
component.Operation();
// 添加额外职责
Console.WriteLine("添加额外职责");
}
}
6. 观察者模式(Observer)
观察者模式定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并自动更新。
示例代码:
public interface IObserver
{
void Update();
}
public class ConcreteObserver : IObserver
{
public void Update()
{
Console.WriteLine("观察者收到通知");
}
}
public interface ISubject
{
void RegisterObserver(IObserver observer);
void RemoveObserver(IObserver observer);
void NotifyObservers();
}
public class ConcreteSubject : ISubject
{
private List<IObserver> observers = new List<IObserver>();
public void RegisterObserver(IObserver observer)
{
observers.Add(observer);
}
public void RemoveObserver(IObserver observer)
{
observers.Remove(observer);
}
public void NotifyObservers()
{
foreach (var observer in observers)
{
observer.Update();
}
}
}
三、总结
本文从零开始,介绍了C#中的经典设计模式,并通过实例解析,让你在实际项目中能够灵活运用。希望本文能帮助你更好地理解和掌握设计模式,从而提高你的编程水平。
