C#中常用的设计模式有很多,以下列举几个常用的:
通过工厂方法创建对象,隐藏对象的实例化过程,提供灵活性和可扩展性。
public interface IAnimal { void Speak(); } public class Cat : IAnimal { public void Speak() { Console.WriteLine("Meow"); } } public class Dog : IAnimal { public void Speak() { Console.WriteLine("Woof"); } } public class AnimalFactory { public IAnimal CreateAnimal(string animalType) { switch (animalType.ToLower()) { case "cat": return new Cat(); case "dog": return new Dog(); default: throw new ArgumentException($"Invalid animal type: {animalType}"); } } } // Usage AnimalFactory animalFactory = new AnimalFactory(); IAnimal animal1 = animalFactory.CreateAnimal("cat"); IAnimal animal2 = animalFactory.CreateAnimal("dog"); animal1.Speak(); // Output: Meow animal2.Speak(); // Output: Woof
保证一个类只有一个实例,并提供一个全局访问点。
public sealed class Singleton { private static readonly Singleton instance = new Singleton(); private Singleton() { } public static Singleton Instance { get { return instance; } } public void DoSomething() { Console.WriteLine("Singleton instance is doing something"); } } // Usage Singleton singleton1 = Singleton.Instance; Singleton singleton2 = Singleton.Instance; Console.WriteLine(singleton1 == singleton2); // Output: True singleton1.DoSomething(); // Output: Singleton instance is doing something
动态地给一个对象添加一些额外的职责,而不影响其他对象。
public interface IComponent { void Operation(); } public class ConcreteComponent : IComponent { public void Operation() { Console.WriteLine("ConcreteComponent.Operation()"); } } public abstract class Decorator : IComponent { private IComponent component; public Decorator(IComponent component) { this.component = component; } public virtual void Operation() { component.Operation(); } } public class ConcreteDecoratorA : Decorator { public ConcreteDecoratorA(IComponent component) : base(component) { } public override void Operation() { base.Operation(); Console.WriteLine("ConcreteDecoratorA.Operation()"); } } public class ConcreteDecoratorB : Decorator { public ConcreteDecoratorB(IComponent component) : base(component) { } public override void Operation() { base.Operation(); Console.WriteLine("ConcreteDecoratorB.Operation()"); } } // Usage IComponent component = new ConcreteComponent(); component = new ConcreteDecoratorA(component); component = new ConcreteDecoratorB(component); component.Operation(); // Output: // ConcreteComponent.Operation() // ConcreteDecoratorA.Operation() // ConcreteDecoratorB.Operation()
定义了一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并自动更新。
// 主题对象 public class Subject { public event EventHandler StateChanged; private int state; public int State { get { return state; } set { state = value; StateChanged?.Invoke(this, EventArgs.Empty); } } } // 观察者对象 public class Observer { private readonly Subject subject; public Observer(Subject subject) { this.subject = subject; subject.StateChanged += HandleStateChanged; } public void HandleStateChanged(object sender, EventArgs e) { Console.WriteLine("State changed to {0}", subject.State); } } // 使用观察者模式 var subject = new Subject(); var observer1 = new Observer(subject); var observer2 = new Observer(subject); subject.State = 1; // 输出:State changed to 1 subject.State = 2; // 输出:State changed to 2
定义了算法族,分别封装起来,让它们之间可以互相替换,使得算法的变化独立于使用它的客户端。
// 策略接口 public interface IPricingStrategy { decimal CalculatePrice(decimal price); } // 策略实现类 public class RegularPricingStrategy : IPricingStrategy { public decimal CalculatePrice(decimal price) { return price; } } public class DiscountPricingStrategy : IPricingStrategy { private decimal discountRate; public DiscountPricingStrategy(decimal discountRate) { this.discountRate = discountRate; } public decimal CalculatePrice(decimal price) { return price * (1 - discountRate); } } // 上下文类 public class Product { private IPricingStrategy pricingStrategy; public Product(IPricingStrategy pricingStrategy) { this.pricingStrategy = pricingStrategy; } public void SetPricingStrategy(IPricingStrategy pricingStrategy) { this.pricingStrategy = pricingStrategy; } public decimal GetPrice(decimal price) { return pricingStrategy.CalculatePrice(price); } }
在这个示例中,IPricingStrategy 接口定义了策略类应实现的方法,而 RegularPricingStrategy 和 DiscountPricingStrategy 是实现策略接口的具体类。Product 类是一个上下文类,其中包含了一个 IPricingStrategy 对象,并且可以在运行时动态更改策略。这使得客户端可以使用 Product 类来计算不同价格的产品,而不必知道实际的算法或逻辑。
定义了一个算法的骨架,将一些步骤延迟到子类中实现,使得子类可以改变算法的某些特定步骤。
public abstract class AbstractClass { public void TemplateMethod() { Operation1(); Operation2(); Operation3(); } protected abstract void Operation1(); protected abstract void Operation2(); protected abstract void Operation3(); } public class ConcreteClass : AbstractClass { protected override void Operation1() { Console.WriteLine("ConcreteClass.Operation1"); } protected override void Operation2() { Console.WriteLine("ConcreteClass.Operation2"); } protected override void Operation3() { Console.WriteLine("ConcreteClass.Operation3"); } }
将一个类的接口转换成客户端所期望的另一个接口,使得原本不兼容的类可以一起工作。
// 目标接口 public interface ITarget { void Request(); } // 源接口 public class Adaptee { public void SpecificRequest() { Console.WriteLine("Adaptee.SpecificRequest"); } } // 适配器 public class Adapter : ITarget { private readonly Adaptee _adaptee; public Adapter(Adaptee adaptee) { _adaptee = adaptee; } public void Request() { _adaptee.SpecificRequest(); } } // 客户端 public class Client { public static void Main() { Adaptee adaptee = new Adaptee(); ITarget target = new Adapter(adaptee); target.Request(); } }
在这个示例中,ITarget 是目标接口,Adaptee 是源接口,Adapter 是适配器。通过适配器,ITarget 接口中的 Request() 方法可以调用 Adaptee 类中的 SpecificRequest() 方法。在客户端中,可以创建一个 Adaptee 对象,然后使用它来创建一个适配器,最后调用适配器的 Request() 方法,以调用 Adaptee 中的 SpecificRequest() 方法。
将一个请求封装为一个对象,从而可以用不同的请求对客户端进行参数化,使得请求的排队或记录日志等操作成为可能。
// 定义命令接口 public interface ICommand { void Execute(); } // 定义具体命令类 public class ConcreteCommand : ICommand { private readonly Receiver _receiver; private readonly string _parameter; public ConcreteCommand(Receiver receiver, string parameter) { _receiver = receiver; _parameter = parameter; } public void Execute() { _receiver.Action(_parameter); } } // 定义命令调用者类 public class Invoker { private ICommand _command; public void SetCommand(ICommand command) { _command = command; } public void ExecuteCommand() { _command.Execute(); } } // 定义接收者类 public class Receiver { public void Action(string parameter) { Console.WriteLine("Receiver is doing action with parameter: {0}", parameter); } } // 客户端代码 class Client { static void Main(string[] args) { // 创建接收者对象 Receiver receiver = new Receiver(); // 创建具体命令对象,并传入接收者对象和参数 ConcreteCommand command = new ConcreteCommand(receiver, "test"); // 创建命令调用者对象,并将命令对象传递给它 Invoker invoker = new Invoker(); invoker.SetCommand(command); // 执行命令 invoker.ExecuteCommand(); } }
这些设计模式可以使程序更加灵活、易于维护和扩展,并且在实际的开发中被广泛应用。
2016 © donet5.comApache Licence 2.0