设计模式之策略模式

来源:互联网 发布:centos下安装mysql 编辑:程序博客网 时间:2024/06/08 07:31

策略模式:“策略”二字等同于算法,当现实系统中需要对算法动态指定,并且可以互相替换,可以抽象出算法的调用接口,具体的算法实现由具体的策略角色去实现,根据里氏替换原则,任何出现父类的地方都可以使用它的子类去替换,这样符合我们的业务需求。

 

案例描述:某家超市国庆节为了促销,某些类商品打折,比如运动鞋打8折、秋装打9折等,张三去购物为了一双运动鞋、一件秋装、一瓶洗发水。。。,张三买完东西回家,心想今天自己总共“赚”了多少钱? 

案例分析:商家对于商品打折可能有很多策略,这里使用策略模式,封装商品打折策略,这样以便以后扩展了打折策略,不用去修改原来的代码,具有很好的灵活性。

模式涉及的角色: 

抽象策略角色:通常由一个接口或者抽象实现;

具体策略角色:包装了相关的算法和行为;

环境角色:包含抽象策略角色的引用,最终供用户使用。

工程结构:

 

 

(1)创建一个Discountable接口,使得每个实现这个接口的类都能够打折

package com.alan.tragedy.goods;public interface Discountable {double getNewPrice() ;}


(2)创建商品类Goods

package com.alan.tragedy.goods;import com.alan.tragedy.goods.utl.Discountor;public class Goods implements Discountable {// 商品的类型private String type;// 商品的名字private String name;// 商品的价格private double price;// 打折策略private Discountor goodsDiscountor;public Goods(String type, String name, double price) {this.type = type;this.name = name;this.price = price;}@Overridepublic String toString(){return "商品类型:"+type+" | 名字:"+name+" | 原始价格"+price+" | 打折后的价格:"+getNewPrice() ;}@Overridepublic double getNewPrice() {// TODO Auto-generated method stubdouble newPrice = price ;if(goodsDiscountor !=null){//根据实现的打折策略来得到打折后的价格newPrice = goodsDiscountor.getNewPrice(newPrice) ;}return newPrice ;}public Discountor getGoodsDiscountor() {return goodsDiscountor;}public void setGoodsDiscountor(Discountor goodsDiscountor) {this.goodsDiscountor = goodsDiscountor;}public String getType() {return type;}public void setType(String type) {this.type = type;}public String getName() {return name;}public void setName(String name) {this.name = name;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}}

(3)创建打折策略的接口Discountor

package com.alan.tragedy.goods.utl;public interface Discountor {//根据原先的价格来取得折扣后的价格double getNewPrice(double oldPrice) ;}

(4)创建打折策略接口的实现类,这边我们简单根据季节来对某个商品来实现不同的打折策略

(4.1)春季的商品打折策略

package com.alan.tragedy.goods;import com.alan.tragedy.goods.utl.Discountor;public class SpringDiscountImpl implements Discountor{//夏季商品的打9折@Overridepublic double getNewPrice(double oldPrice) {return oldPrice * 0.9;}}

(4.2)秋季的商品打折策略

package com.alan.tragedy.goods;import com.alan.tragedy.goods.utl.Discountor;public class AutomDiscountor implements Discountor{@Overridepublic double getNewPrice(double oldPrice) {//秋季打68折return oldPrice * 0.68;}}

(5)创建一个测试类

package com.alan.tragedy.goods;public class Client {public static void main(String[] args) {//创建一个商品:type:衣服,name:上衣,price:235.0¥Goods goods = new Goods("衣服","上衣",235.0) ; //春季打折策略goods.setGoodsDiscountor(new SpringDiscountImpl()) ;System.out.println("春季---〉"+goods);//秋季打折策略goods.setGoodsDiscountor(new AutomDiscountor()) ;System.out.println("秋季---〉"+goods);}}

输出的结果:

春季---〉商品类型:衣服 | 名字:上衣 | 原始价格235.0 | 打折后的价格:211.5秋季---〉商品类型:衣服 | 名字:上衣 | 原始价格235.0 | 打折后的价格:159.8







 

原创粉丝点击