1. 什么是策略模式?
策略模式针对的是在不同的环境中,客户端选择使用不同的策略。
2. 为什么使用策略模式?
当增加一种新的算法的时候,只需要在客户端登记即可。相当于“可插入的算法”。扩展性更好。
3. 什么时候使用策略模式?
如果一个系统需要动态的从几种算法中选择一种算法。则使用策略模式。
4. 策略模式在java中的应用
比如说 awt包中的Container提供了不同的排列方式,BorderLayout , FlowLayout,BirdLayout等。
5. 实际的应用: 贩卖图书的电子商城系统对于不同的书籍,使用不同的打折扣的方法。
代码:
package com.huxin.javatest.strategy;
import java.util.Iterator;
public class Context {
private AbstractStrategy abstractStrategy;
public Context(AbstractStrategy abstractStrategy){
this.abstractStrategy = abstractStrategy;
}
public double calculateDiscount(){
return abstractStrategy.getDiscount();
}
}
package com.huxin.javatest.strategy;
abstract public class AbstractStrategy {
private int number;
private double price;
public abstract double getDiscount();
}
package com.huxin.javatest.strategy;
public class FirstStrategy extends AbstractStrategy{
private int number;
private double price;
public FirstStrategy(double price,int number){
this.price = price;
this.number = number;
}
public double getDiscount() {
//第一种策略是不打折
return 0;
}
}
package com.huxin.javatest.strategy;
public class SecondStrategy extends AbstractStrategy{
private int number;
private double price;
public SecondStrategy(double price,int number){
this.price = price;
this.number = number;
}
public double getDiscount() {
//第二种策略是单价少3块钱
return number * 3;
}
}
package com.huxin.javatest.strategy;
public class ThirdStrategy extends AbstractStrategy{
private int number;
private double price;
private double percent;
public ThirdStrategy(double price,int number){
this.price = price;
this.number = number;
}
public double getPercent() {
return percent;
}
public void setPercent(double percent) {
this.percent = percent;
}
public double getDiscount() {
//根据百分比进行打折
return price * percent;
}
}
package com.huxin.javatest.strategy;
import java.util.HashSet;
import java.util.Set;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
ThirdStrategy abstractStrategy = new ThirdStrategy(80.0,20);
abstractStrategy.setPercent(0.8);
Context c = new Context(abstractStrategy);
double discount = c.calculateDiscount();
System.out.println(discount);
}
}