设为首页 加入收藏

TOP

策略模式 和 模版方法模式(Template method)(一)
2014-11-24 12:02:19 来源: 作者: 【 】 浏览:76
Tags:策略 模式 模版 方法 Template method
1.策略模式
1.1 策略模式
策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。
策略模式让算法独立于使用它的客户而独立变化。
策略模式属于对象的行为模式。其用意是针对一组算法,将每一个算法封装到具有
共同接口的独立的类中,从而使得它们可以相互替换。策略模式使得算法可以在不影响到
客户端的情况下发生变化。
1.2 策略模式的组成
(1)抽象策略角色: 策略类,通常由一个接口或者抽象类实现。
(2)具体策略角色:包装了相关的算法和行为。
类图如下:
1.3 使用场景
假设:现在要设计一个贩卖各类书籍的电子商务网站的购物车系统。
一个最简单的情况就是把所有货品的单价乘上数量,但是实际情况肯定比这要复杂。
比如,本网站可能对所有的高级会员提供每本20%的促销折扣;对中级会员提供每本
10%的促销折扣;对初级会员没有折扣。
根据描述,折扣是根据以下的几个算法中的一个进行的:
 算法一:对初级会员没有折扣。
 算法二:对中级会员提供10%的促销折扣。
 算法三:对高级会员提供20%的促销折扣。
实现代码如下:
[java]
/**
* @Title:商品抽象折扣类
* @Description:TODO
* @Company: Orclight's Studio
* @author: shuzl 2013-3-12 下午03:24:53
* @motto: Never put off what you can do today until Tomorrow
* @version 1.0.0
*/
public interface MemberStrategy {
public double discountPrice(double bookPrice);
}
[java]
/**
* @Title:初级会员--折扣类
* @Description:TODO
* @Company: Orclight's Studio
* @author: shuzl 2013-3-12 下午03:53:59
* @motto: Never put off what you can do today until Tomorrow
* @version 1.0.0
*/
public class JuniorMemberStrategy implements MemberStrategy{
public double discountPrice(double bookPrice) {
return bookPrice;
}
}
[java]
/**
* @Title:中级会员--折扣类
* @Description:TODO
* @Company: Orclight's Studio
* @author: shuzl 2013-3-12 下午03:58:01
* @motto: Never put off what you can do today until Tomorrow
* @version 1.0.0
*/
public class InterMediateMemberStrategy implements MemberStrategy{
@Override
public double discountPrice(double bookPrice) {
return bookPrice*0.9;
}
}
[java]
/**
* @Title:高级会员--折扣类
* @Description:TODO
* @Company: Orclight's Studio
* @author: shuzl 2013-3-12 下午03:59:30
* @motto: Never put off what you can do today until Tomorrow
* @version 1.0.0
*/
public class AdvancedMemberStrategy implements MemberStrategy{
@Override
public double discountPrice(double bookPrice) {
return bookPrice*0.8;
}
}
[java]
/**
* @Title: 图书价格类
* @Description:TODO
* @Company: Orclight's Studio
* @author: shuzl 2013-3-12 下午04:15:57
* @motto: Never put off what you can do today until Tomorrow
* @version 1.0.0
*/
public class BookPrice {
private MemberStrategy strategy;
private double price;
/**
* @param strategy
*/
public BookPrice(MemberStrategy strategy,double price) {
super();
this.strategy = strategy;
this.price=price;
}
/**
*
* getRealBookPrice(获取折扣后的价格)
* @return double
* @createDate 2013-3-12 下午04:30:26
* @since 1.0.0
*/
public double getRealBookPrice() {
return strategy.discountPrice(this.price);
}
public MemberStrategy getStrategy() {
return strategy;
}
public void setStrategy(MemberStrategy strategy) {
this.strategy = strategy;
}
}
[java]
/**
* @Title:图书打折后的价格--测试类
* @Description:TODO
* @Company: Orclight's Studio
* @author: shuzl 2013-3-12 下午04:17:23
* @motto: Never put off what you can d
首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇对象按照某属性升序,降序 下一篇Spring AOP记录系统日志

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: