package java_learning;
import java.text.NumberFormat;
import java.util.ArrayList;
//开闭原则:软件实体变化应该 对扩展开放,对修改关闭.
//其含义是说一个软件实体应该通过扩展来实现变化,而不是通过修改已有的代码来实现变化。
public class OpenAndClose {
private final static ArrayList<IBook> bookList = new ArrayList<IBook>();
//static静态模块初始化数据,实际项目中一般是由持久层完成
static{
/*
bookList.add(new NovelBook("天龙八部",3200,"金庸"));
bookList.add(new NovelBook("巴黎圣母院",5600,"雨果"));
bookList.add(new NovelBook("悲惨世界",3500,"雨果"));
bookList.add(new NovelBook("金瓶梅",4300,"兰陵笑笑生"));
*/
bookList.add(new OffNovelBook("天龙八部",3200,"金庸"));
bookList.add(new OffNovelBook("巴黎圣母院",5600,"雨果"));
bookList.add(new OffNovelBook("悲惨世界",3500,"雨果"));
bookList.add(new OffNovelBook("金瓶梅",4300,"兰陵笑笑生"));
}
//模拟书店买书
public static void main(String[] args) {
NumberFormat formatter = NumberFormat.getCurrencyInstance();
formatter.setMaximumFractionDigits(2);
System.out.println("-----------书店卖出去的书籍记录如下:-----------");
for(IBook book:bookList){
System.out.println("书籍名称:" + book.getName()+"\t书籍作者:" +
book.getAuthor()+"\t书籍价格:"+ formatter.format (book.getPrice()/
100.0)+"元");
}
}
}
interface IBook {
//书籍有名称
public String getName();
//书籍有售价
public int getPrice();
//书籍有作者
public String getAuthor();
}
class NovelBook implements IBook {
//书籍名称
private String name;
//书籍的价格
private int price;
//书籍的作者
private String author;
//通过构造函数传递书籍数据
public NovelBook(String _name,int _price,String _author){
this.name = _name;
this.price = _price;
this.author = _author;
}
//获得作者是谁
public String getAuthor() {
return this.author;
}
//书籍叫什么名字
public String getName() {
return this.name;
}
//获得书籍的价格
public int getPrice() {
return this.price;
}
}
//全球经济开始下滑,
//对零售业影响比较大,书店为了生存开始打折销售:所有40元以上的书籍9折销售,其他的8
//折销售。对已经投产的项目来说,这就是一个变化,我们应该如何应对这样一个需求变化?
/* 通过扩展实现变化*/
class OffNovelBook extends NovelBook{
public OffNovelBook(String _name, int _price, String _author) {
super(_name, _price, _author);
}
public int getPrice() {
int selfPrice;//原价
int OffPrice;
selfPrice = super.getPrice();
if(selfPrice>4000){ //原价大于40元,则打9折
OffPrice = selfPrice * 90 /100;
}else{
OffPrice = selfPrice * 80 /100;
}
return OffPrice;
}
}
/*注意 开闭原则对扩展开放,对修改关闭,并不意味着不做任何修改,低层模块的变
更,必然要有高层模块进行耦合,否则就是一个孤立无意义的代码片段。*/
OpenAndClose
最新推荐文章于 2022-04-09 13:10:10 发布