策略模式
一、题目:
设计一个网上书店,该系统中所有的计算机图书(ComputerBook),每本都有10%的折扣;所有的语言类图书(LanguageBook),每本有2元的折扣;小说类图书以每100元有10元的折扣,用策略模式设计该系统
(1)绘制策略模式结构视图
(2)给出实例类图并实现代码
二、所用模式结构视图:
三、实例类图:
四、实例实现代码:
(因为区分,所以在类的前面加了Gj19)
策略接口
package gjStrategyPattern;
/**
* 策略接口
* @author gong
*
*/
public interface Gj19BookStrategy {
double calPrice(double price);
}
计算机书籍打折策略
package gjStrategyPattern;
/**
* 计算机书籍打折策略
* @author gong
*
*/
public class Gj19ComputerStrategy implements Gj19BookStrategy{
/**
* 具体的打折策略
*/
@Override
public double calPrice(double price) {
System.out.println("所有的计算机图书 每本都有10%的折扣");
return price*0.9D;
}
public Gj19ComputerStrategy() {
}
}
语言书籍打折策略类
package gjStrategyPattern;
/**
* 语言书籍打折策略类
* @author gong
*
*/
public class Gj19LanguageStrategy implements Gj19BookStrategy{
/**
* 每本书减去2元
*/
@Override
public double calPrice(double price) {
System.out.println("语言类图书 每本有2元的折扣");
return price-2.0D;
}
public Gj19LanguageStrategy() {
}
}
小说的打折策略类
package gjStrategyPattern;
/**
* 小说的打折策略类
*
* @author gong
*
*/
public class Gj19NovelStrategy implements Gj19BookStrategy {
@Override
public double calPrice(double price) {
System.out.println("小说类图书以每100元有10元的折扣");
int p = (int) price;
return price-(double)(p/100*10);
}
public Gj19NovelStrategy() {
}
}
计算价格的类
package gjStrategyPattern;
/**
* 计算价格的类
* @author gong
*
*/
public class Gj19Price {
/**
* 创建抽象的策略模式
*/
private Gj19BookStrategy bookStrategy;
public Gj19Price(Gj19BookStrategy bookStrategy){
this.bookStrategy = bookStrategy;
}
public double sum(double price){
return this.bookStrategy.calPrice(price);
}
}
策略模式客户端
package gjStrategyPattern;
/**
* 策略模式客户端
* @author gong
*
*/
public class Client {
//调用计算机书籍的打折策略
public static void main(String[] args) {
//定义具体的打折策略
Gj19ComputerStrategy computerStrategy = new Gj19ComputerStrategy();
Gj19LanguageStrategy gj19LanguageStrategy = new Gj19LanguageStrategy();
Gj19NovelStrategy gj19NovelStrategy = new Gj19NovelStrategy();
//原价 折后价
double price = 520.0D;
double discountPrice;
//计算机书籍打折策略
System.out.println("========================计算机书籍打折策略=======================");
System.out.println("打折前的价格为:"+price);
discountPrice = new Gj19Price(computerStrategy).sum(price);
System.out.println("打折后的价格为:"+discountPrice);
System.out.println("================================================================");
//语言书籍打折策略
System.out.println("=========================语言书籍打折策略========================");
System.out.println("打折前的价格为:"+price);
discountPrice = new Gj19Price(gj19LanguageStrategy).sum(price);
System.out.println("打折后的价格为:"+discountPrice);
System.out.println("================================================================");
//小说书籍打折策略
System.out.println("==========================小说书籍打折策略=======================");
System.out.println("打折前的价格为:"+price);
discountPrice = new Gj19Price(gj19NovelStrategy).sum(price);
System.out.println("打折后的价格为:"+discountPrice);
}
}
五、运行结果:
更多推荐
设计模式练习(19)——策略模式
发布评论