开闭原则概述
开放封闭原则,简称开闭原则,是指一个软件实体应当对扩展开放,对修改关闭,即在设计一个模块时,应当使这个模块在不被修改的前提下进行扩展。
开闭原则实现书店打折销售
需求变更:
假设书店原有4本书,现在按照9折出售图书,
打印输出打折前后的图书信息。
对修改关闭的原则,不能直接修改IBook接口和Novel类,
而是通过增加一个子类OffNovelBook来完成。
代码实现
(1)IBook接口
package bookStoreDemo;
public interface IBook {
//接口中一般写抽象方法
public String getName();
public double getPrice();
public String getAuthor();
}
(2)NovelBook接口实现类
package bookStoreDemo;
public class NovelBook implements IBook{
//接口的实现类
private String name;
private double price;
private String author;
public NovelBook() {
//默认的构造方法
}
public NovelBook(String name, double price, String author) {
this.name = name;
this.price = price;
this.author = author;
}
//自动生成get和set方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
(3)OffNovelBook类
package bookStoreDemo;
public class OffNovelBook extends NovelBook{
public OffNovelBook(String name, double price, String author) {
super(name, price, author);
}
public double getPrice(){
double beforePrice = super.getPrice();
double currentPrice=0;
currentPrice=beforePrice*90/100;
return currentPrice;
}
}
(4)BookStore类
package bookStoreDemo;
/*开闭原则实现书店打折销售
需求变更:
假设书店原有4大名著,现在按照9折出售图书,
打印输出打折前后的图书信息。
对修改关闭的原则,不能直接修改IBook接口和Novel类,
而是通过增加一个子类OffNovelBook来完成。
*/
import java.util.ArrayList;
public class BookStore {
//静态代码块只执行一次,可以视为常量
private static final ArrayList<IBook> bookList=new ArrayList<IBook>();
static{
bookList.add(new OffNovelBook("设计模式",40,"张凯"));
bookList.add(new OffNovelBook("机器学习",50,"王磊"));
bookList.add(new OffNovelBook("Vue实战",40,"尤里溪"));
bookList.add(new OffNovelBook("人工智能",40,"王万良"));
}
public static void main(String[] args) {
System.out.println("---------------书籍打9折后的价格明细-----------------");
for(IBook book:bookList){
System.out.println("书籍名称:" + book.getName()+"\t书籍作者:" +
book.getAuthor()+ "\t书籍价格:" + book.getPrice()+"元");
}
}
}