标签:new 优点 rac 业务规则 value imp 定义 cal public
一 策略模式
public interface MemberStrategy { /** * 计算图书的价格 * @param booksPrice 图书的原价 * @return 计算出打折后的价格 */ public double calcPrice(double booksPrice); } public class PrimaryMemberStrategy implements MemberStrategy { @Override public double calcPrice(double booksPrice) { System.out.println("对于初级会员的没有折扣"); return booksPrice; } } public class IntermediateMemberStrategy implements MemberStrategy { @Override public double calcPrice(double booksPrice) { System.out.println("对于中级会员的折扣为10%"); return booksPrice * 0.9; } } public class AdvancedMemberStrategy implements MemberStrategy { @Override public double calcPrice(double booksPrice) { System.out.println("对于高级会员的折扣为20%"); return booksPrice * 0.8; } } public class Price { //持有一个具体的策略对象 private MemberStrategy strategy; /** * 构造函数,传入一个具体的策略对象 * @param strategy 具体的策略对象 */ public Price(MemberStrategy strategy){ this.strategy = strategy; } /** * 计算图书的价格 * @param booksPrice 图书的原价 * @return 计算出打折后的价格 */ public double quote(double booksPrice){ return this.strategy.calcPrice(booksPrice); } } public class Client { public static void main(String[] args) { //选择并创建需要使用的策略对象 MemberStrategy strategy = new AdvancedMemberStrategy(); //创建环境 Price price = new Price(strategy); //计算价格 double quote = price.quote(300); System.out.println("图书的最终价格为:" + quote); } }
二 状态模式
/// <summary> /// 电灯类,对应模式中的Context类 /// </summary> public class Light { private LightState state; public Light(LightState state) { this.state = state; } /// <summary> /// 按下电灯开关 /// </summary> public void PressSwich() { state.PressSwich(this); } public LightState State { get { return state; } set { state = value; } } } /// <summary> /// 抽象的电灯状态类,相当于State类 /// </summary> public abstract class LightState { public abstract void PressSwich(Light light); } /// <summary> /// 具体状态类, 开 /// </summary> public class On : LightState { /// <summary> /// 在开状态下,按下开关则切换到关的状态。 /// </summary> /// <param name="light"></param> public override void PressSwich(Light light) { Console.WriteLine("Turn off the light."); light.State = new Off(); } } /// <summary> /// 具体状态类,关 /// </summary> public class Off: LightState { /// <summary> /// 在关状态下,按下开关则打开电灯。 /// </summary> /// <param name="light"></param> public override void PressSwich(Light light) { Console.WriteLine("Turn on the light."); light.State = new On(); } } class Program { static void Main(string[] args) { // 初始化电灯,原始状态为关 Light light = new Light(new Off()); // 第一次按下开关,打开电灯 light.PressSwich(); // 第二次按下开关,关闭电灯 light.PressSwich(); Console.Read(); } }
三 两种模式的区别
联系:
状态模式和策略模式都是为具有多种可能情形设计的模式,把不同的处理情形抽象为一个相同的接口,符合对扩展开放,对修改封闭的原则。
标签:new 优点 rac 业务规则 value imp 定义 cal public
原文地址:http://www.cnblogs.com/liufei1983/p/7105441.html