我的专业网站建设策划书,建筑工程分包平台,城厢区建设局网站,上海的装修公司前十强有哪些策略模式是一种定义一系列算法的方法#xff0c;以相同的方式调用不同的算法#xff0c;减少了各种算法类与使用算法类之间的耦合。
它的重心不是如何实现算法#xff0c;而是如何组织#xff0c;调用这些算法。从而让程序结构更灵活#xff0c;具有更好的维护性和扩展性…策略模式是一种定义一系列算法的方法以相同的方式调用不同的算法减少了各种算法类与使用算法类之间的耦合。
它的重心不是如何实现算法而是如何组织调用这些算法。从而让程序结构更灵活具有更好的维护性和扩展性。
代码实现 //算法策略接口
public interface IStrategy
{int GetPayment(int charge);
}
//策略A
public class CashNormarl : IStrategy
{public int GetPayment(int charge){return charge;}
}
//策略B
public class CashReturn : IStrategy
{public int GetPayment(int charge){if(charge 300){return charge-100;}}
}
//组织策略上下文
public class CashContext
{IStrategy _strategy ;public CashContext(IStrategy strategy){_strategy strategy;}public int GetPayment(int charge){return _strategy.GetPayment();}
}//客户端调用
int charge 1000;
var cash CashContext(new CashReturn());
var payment cash.GetPayment(charge ); 还可以通过简单工厂模式来优化 组织策略上下文类 让客户端与算法实现类完全解耦