开闭原则概述
- 一个软件实体如类,模块和函数应该对扩展开放(对提供方),对修改关闭(使用方)。具体做法是用抽象来构建框架,用实现来扩展新的细节。
- 当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是在修改软件实体的源代码或者二进制代码的前提实现变化
问题:
怎么样的代码改动可以定义为扩展,怎么样的代码改动定义为为修改,怎样才算满足开闭原则
示例代码,图书价格,图书售卖
public interface IBook {
String getName();
int getPrice();
String getAuthor();
}
public 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 getName() {
return name;
}
public int getPrice() {
return price;
}
public String getAuthor() {
return author;
}
}
图书售卖
import java.util.ArrayList;
public class BookStore {
private final static ArrayList<IBook> bookList = new ArrayList<IBook>();
static {
bookList.add(new NovelBook("天龙八部",3200,"金庸"));
bookList.add(new NovelBook("巴黎圣母院",5600,"雨果"));
bookList.add(new NovelBook("战争和和平",3600,"托尔斯泰"));
bookList.add(new NovelBook("红楼梦",4500,"曹雪芹"));
}
public static void main(String[] args) {
System.out.println("图书记录如下");
for (IBook iBook:bookList) {
System.out.println("书籍名称:" + iBook.getName() +
"\t书籍作者" + iBook.getAuthor() +
"\t书籍价格" + iBook.getPrice()/100 + "¥元");
}
}
}
如果售卖对图书扩展,价格高于40元以上打0.8折,40元下打0.9折。
第一:改动源代码,违背开闭原则。会影响原来价格
第二:对图书类扩展
public class NovelOffBook extends NovelBook{
public NovelOffBook(String name, int price, String author) {
super(name, price, author);
}
@Override
public int getPrice() {
int price = super.getPrice();
int offPrice = 0;
if (price < 4000) {
offPrice = price * 90 / 100;
} else {
offPrice = price * 80 / 100;
}
return offPrice;
}
}
网友评论