原博主地址:(https://blog.csdn.net/LoveLion/article/details/17517213)
策略模式(Strategy Pattern):定义一系列算法类,将每一个算法封装起来,并让它们可以相互替换,策略模式让算法独立于使用它的客户而变化,也称为政策模式(Policy)。策略模式是一种对象行为型模式。
票类
package test2019.mon02.策略模式;
/**
* Filename: Plane.java
* Description:
* Company: sendinfo.com.cn Inc.
* @author: guzhangyan
* @date: 2019年2月21日 下午5:29:48
*/
public class Ticket {
private Desicount desicount;
private double price;
public Desicount getDesicount() {
return desicount;
}
public void setDesicount(Desicount desicount) {
this.desicount = desicount;
}
public double getPrice() {
return desicount.getPrice(price);
}
public void setPrice(double price) {
this.price = price;
}
}
属性接口
package test2019.mon02.策略模式;
/**
* Filename: PlaneType.java
* Description:
* Company: sendinfo.com.cn Inc.
* @author: guzhangyan
* @date: 2019年2月21日 下午5:31:35
*/
public interface Desicount {
public double getPrice(double price);
}
属性实现类
package test2019.mon02.策略模式;
/**
* Filename: ChildDesicount.java Description: Company: sendinfo.com.cn Inc.
*
* @author: guzhangyan
* @date: 2019年2月21日 下午5:34:52
*/
public class ChildDesicount implements Desicount {
@Override
public double getPrice(double price) {
System.out.print("儿童票:");
if (price > 10) {
return price - 10;
}
return price;
}
}
package test2019.mon02.策略模式;
/**
* Filename: ChildDesicount.java Description: Company: sendinfo.com.cn Inc.
*
* @author: guzhangyan
* @date: 2019年2月21日 下午5:34:52
*/
public class StudentDesicount implements Desicount {
@Override
public double getPrice(double price) {
System.out.print("学生票:");
return price*0.8;
}
}
package test2019.mon02.策略模式;
/**
* Filename: ChildDesicount.java Description: Company: sendinfo.com.cn Inc.
*
* @author: guzhangyan
* @date: 2019年2月21日 下午5:34:52
*/
public class VipDesicount implements Desicount {
@Override
public double getPrice(double price) {
System.out.print("VIP票:");
System.out.println("加积分");
return price*0.5;
}
}
测试
package test2019.mon02.策略模式;
/**
* Filename: Test.java
* Description:
* Company: sendinfo.com.cn Inc.
* @author: guzhangyan
* @date: 2019年2月21日 下午5:38:54
*/
public class Test {
public static void main(String args[]) {
Ticket mt = new Ticket();
double originalPrice = 60.0;
double currentPrice;
mt.setPrice(originalPrice);
System.out.println("原始价为:" + originalPrice);
System.out.println("---------------------------------");
Desicount discount;
discount = (Desicount)XmlUtil.getBean("discount"); //读取配置文件并反射生成具体折扣对象
mt.setDesicount(discount); //注入折扣对象
currentPrice = mt.getPrice();
System.out.println("折后价为:" + currentPrice);
}
}
//XmlUtil请看桥接模式