1、定义
开闭原则,对于扩展是开放的,对于修改是关闭。
OCP_Diagram.png
2、实现
(1)创建书籍接口
interface IBook {
String getName();
int getPrice();
String getAuthor();
}
(2)创建计算机书籍接口
interface IComputerBook extends IBook {
public String getScope();
}
(3)实现小说类
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;
}
@Override
public String getName() {
return name;
}
@Override
public int getPrice() {
return price;
}
@Override
public String getAuthor() {
return author;
}
}
(4)实现计算机书籍类
class ComputerBook implements IComputerBook {
private String name;
private int price;
private String author;
private String scope;
public ComputerBook(String name, int price, String author, String scope) {
this.name = name;
this.price = price;
this.author = author;
this.scope = scope;
}
@Override
public String getName() {
return name;
}
@Override
public int getPrice() {
return price;
}
@Override
public String getScope() {
return scope;
}
@Override
public String getAuthor() {
return author;
}
}
(4)实现书店类
class BookStore {
private final static ArrayList<IBook> sBookList = new ArrayList<IBook>();
static {
sBookList.add(new NovelBook("天龙八部", 3200, "金庸"));
sBookList.add(new NovelBook("巴黎圣母院", 5600, "雨果"));
sBookList.add(new NovelBook("悲催世界", 3500, "雨果"));
sBookList.add(new NovelBook("金瓶梅", 4300, "兰陵笑笑生"));
sBookList.add(new ComputerBook("Think in Java", 5800, "Bruce Eckel", "编程语言"));
}
public static void main(String[] args) throws IOException {
NumberFormat format = NumberFormat.getCurrencyInstance();
format.setMaximumFractionDigits(2);
Log.d("JimmyZhang", "----书店卖出去的书籍记录如下---");
for (IBook book : sBookList) {
Log.d("JimmyZhang", "书籍名称:" + book.getName()
+ " 书籍作者:" + book.getAuthor()
+ " 书籍价格:" + format.format(book.getPrice() / 100.00) + "元");
}
}
}