Java设计模式:策略Strategy模式,以电影票折扣策略为例

/**
 * 折扣策略。
 * 
 * @author zhangfly
 *
 */
public interface DiscountStrategy {
	public double getDiscountPrice(double value);
}

 

/**
 * 电影票模型。
 * 
 * @author zhangfly
 *
 */
public class MovieTicket {
	private double price;
	private DiscountStrategy strategy;

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

	// 设置电影票打折策略。
	public void setDiscountStrategy(DiscountStrategy strategy) {
		this.strategy = strategy;
	}

	// 原价。
	public double getPrice() {
		return price;
	}

	// 折扣价。
	public double getDiscountPrice() {
		// 折扣票价计算策略。
		return strategy.getDiscountPrice(this.price);
	}
}

 

/**
 * 学生,折扣策略:打八折。
 * 
 * @author zhangfly
 *
 */
public class StudentDiscountStrategy implements DiscountStrategy {

	@Override
	public double getDiscountPrice(double value) {
		return value * 0.8;
	}
}

 


/**
 * VIP,电影票折扣策略半价。
 * 
 * @author zhangfly
 *
 */
public class VIPDiscountStrategy implements DiscountStrategy {

	@Override
	public double getDiscountPrice(double value) {
		return value * 0.5;
	}
}

 

public class Test {
	public Test() {
		double price = 100;

		MovieTicket movieTicket = new MovieTicket();
		movieTicket.setPrice(price);
		System.out.println("电影票原价: " + movieTicket.getPrice());

		DiscountStrategy studentStrategy = new StudentDiscountStrategy();
		movieTicket.setDiscountStrategy(studentStrategy);
		System.out.println("学生票价: " + movieTicket.getDiscountPrice());

		DiscountStrategy vipStrategy = new VIPDiscountStrategy();
		movieTicket.setDiscountStrategy(vipStrategy);
		System.out.println("VIP票价: " + movieTicket.getDiscountPrice());
	}

	public static void main(String[] args) {
		new Test();
	}
}

 

输出:

电影票原价: 100.0
学生票价: 80.0
VIP票价: 50.0

 

你可能感兴趣的:(Java,设计模式,设计模式与架构设计)