在软件的构建过程中,某些对象使用的算法可能多种多样,如果将这些算法直接编码到使用的类中的,这些类的维护旧就成为一个问题。解决的思路是“封装变化点”,将算法首先抽象出一个父类,然后在使用这些算法的类中只保留父类的引用,而传递的就是具体类。 实现代码: class Program { static void Main(string[] args) { // 这里动态改变,动态更改算法。 Car car = new Car(new ProcessStrtategyA()); } } enum CarType { A, B, C, D } // 算法抽象 interface IProcessStrtategy { void Process(); } // 具体算法 public class ProcessStrtategyA : IProcessStrtategy { public void Process() { } } class Car { IProcessStrtategy processStrtategy; public void SomeMethod() { processStrtategy.Process(); } public Car(IProcessStrtategy s) { this.processStrtategy = s; } public int[] GetAllAlignment(CarType type) { if (type == CarType.A) { ProcessA(); } else if (type == CarType.B) { ProcessB(); } else if(type == CarType.c) { ProcessC(); } else { ProcessD(); } } protected void ProcessA() { } protected void ProcessB() { } protected void ProcessC() { } protected void ProcessD() { } } class ProcessStrtategyB : IProcessStrtategy { public void Process() { } } 相关文章: 2021-09-05 2021-07-21 2021-12-28 2021-11-27 2022-02-25 2022-12-23 2021-11-11 2021-06-03