后端开发C#C#中的多态及switch
L X Y
简单工厂模式:用多态优化对象创建(基于订单处理系统案例)
问题场景
当业务需要根据不同条件创建不同对象时,常见做法是使用switch或if-else分支:
1 2
| if(orderType == "Book") CreateBookHandler(); else if(orderType == "Video") CreateVideoHandler();
|
这种写法会导致:
新增类型需修改核心逻辑
创建逻辑散落在各处
单元测试困难
解决方案:简单工厂+多态
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| public interface IOrderHandler { void Handle(); }
public class BookOrderHandler : IOrderHandler { public void Handle() => Console.WriteLine("处理书籍订单"); }
public class VideoOrderHandler : IOrderHandler { public void Handle() => Console.WriteLine("处理视频订单"); }
public class OrderProcessor { public IOrderHandler Create(string orderType) { switch (orderType) { case "Book": return new BookOrderHandler(); case "Video": return new VideoOrderHandler(); default: throw new ArgumentException("无效订单类型"); } } public void Process(string orderType) { IOrderHandler handler = Create(orderType); handler.Handle(); } }
|
设计原则
开闭原则
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class MusicOrderHandler : IOrderHandler { public void Handle() => Console.WriteLine("处理音乐订单"); } public class OrderProcessor { public IOrderHandler Create(string orderType) { switch (orderType) { case "Book": return new BookOrderHandler(); case "Video": return new VideoOrderHandler(); case "Music": return new MusicOrderHandler(); default: throw new ArgumentException("无效订单类型"); } } }
|
单一职责原则
OrderProcessor只负责流程控制
具体处理逻辑由各实现类完成
依赖倒置原则
1 2 3 4 5
| public void Process(string orderType) { IOrderHandler handler = Create(orderType); handler.Handle(); }
|