定义:
策略模式定义了一系列的算法,并将每一个算法封装起来,使它们可以互相替换
个人理解:
类似委托的作用,将算法通过客户端传入,起到订制的作用
客户端:
IActive active = new HighActive(); decimal payPrice = new ActiveExecutor().Execute(active);
策略执行类:
public class ActiveExecutor { public decimal Execute(IActive active) { decimal orderPrice = 200M; return active.Rule(orderPrice); } }
策略类:
public interface IActive { //int DiscountType { get; } decimal Rule(decimal orderPrice); } public class LowActive : IActive { public decimal Rule(decimal orderPrice) { if (orderPrice < 100M) { return orderPrice - 1M; } else { return orderPrice - 5M; } } } public class MiddleActive : IActive { public decimal Rule(decimal orderPrice) { if (orderPrice < 100M) { return orderPrice - 10M; } else { return orderPrice - 20M; } } } public class HighActive : IActive { public decimal Rule(decimal orderPrice) { if (orderPrice < 100M) { return orderPrice - 20M; } else { return orderPrice - 50M; } } }