首页 > 代码库 > strategy(策略模式)

strategy(策略模式)

DiscountStrategy.java

package edu.strategy;

abstract public class DiscountStrategy
{
    abstract public double calculateDiscount();
}

FlatRateStrategy.java

package edu.strategy;

public class FlatRateStrategy extends DiscountStrategy
{
    private double amount;
    private double price = 0;
    private int copies = 0;

    public FlatRateStrategy(double price, int copies)
    {
        this.setPrice(price);
        this.copies = copies;
    }

    public double getAmount()
    {
        return amount;
    }

    public void setAmount(double amount)
    {
        this.amount = amount;
    }

    public double calculateDiscount()
    {
        return copies * amount;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

NoDiscountStrategy.java

package edu.strategy;

public class NoDiscountStrategy extends DiscountStrategy {
    private double price = 0.0;
    private int copies = 0;

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getCopies() {
        return copies;
    }

    public void setCopies(int copies) {
        this.copies = copies;
    }

    public NoDiscountStrategy(double price, int copies) {
        this.price = price;
        this.copies = copies;
    }

    public double calculateDiscount() {
        return 0.0;
    }
}

PercentageStrategy.java

package edu.strategy;

public class PercentageStrategy extends DiscountStrategy
{
    private double percent = 0.0;
    private double price = 0.0;
    private int copies = 0;

    public PercentageStrategy(double price, int copies)
    {
        this.price = price;
        this.copies = copies;
    }

    public double getPercent()
    {
        return percent;
    }

    public void setPercent(double percent)
    {
        this.percent = percent;
    }

    public double calculateDiscount()
    {
        return copies * price * percent;
    }

}

调用如下

 

Context.java

package edu.strategy.test;

public class Context {
    private Strategy strategy;
    /*
     * 策略方法
     */
    public void contextInterface(){
        strategy.strategyInterface();
    }
}

ContextStrategy.java

package edu.strategy.test;

public class ContextStrategy extends Strategy {
    /*
     * 策略方法
     * 
     * @see edu.strategy.Strategy#strategyInterface()
     */
    @Override
    public void strategyInterface() {

    }

}

Strategy.java

package edu.strategy.test;

abstract public class Strategy {
    /*
     * 策略方法
     */
    public abstract void strategyInterface();
}