为什么没有说是面向对象6大原则,为什么没有将开闭原则包括进去?
开闭原则是最基础的一个原则,前面5个原则就是它的具体形态,开闭原则才是他们的接口。
IBook作为一个接口,里面有三个方法,而小说NovelBook是一个具体的实现类,是所有小说的总称,BookStore指的是书店。
public interface IBook { public String getName(); public int getPrice(); public String getAuthor(); }
public class NovelBook implements IBook { private String name; private int price; private String autor; public NovelBook(String name,int price,String autor){ this.name=name; this.price=price; this.autor=autor; } public String getAuthor() { return this.autor; } public String getName() { return this.name; } public int getPrice() { return this.price; } }
public class Store { private final static ArrayList<IBook> booklist = new ArrayList<IBook>(); static { // 静态模块加载数据,实际项目一般由持久层完成 booklist.add(new NovelBook("巴黎圣母院", 3200, "雨果")); booklist.add(new NovelBook("悲惨世界", 5600, "雨果")); booklist.add(new NovelBook("天龙八部", 4800, "金庸")); booklist.add(new NovelBook("挪威的森林", 2200, "村上春树")); } public static void main(String[] args) { NumberFormat format = NumberFormat.getCurrencyInstance(); format.setMaximumFractionDigits(2); System.out.println("-------------书店卖出去的书籍记录如下---------------"); for (IBook book : booklist) { System.out.println("书籍名称:" + book.getName() + "\t书籍作者:" + book.getAuthor() + "\t书籍价格:" + format.format(book.getPrice() / 100.0) + "元"); } } }
public class OffNovelBook extends NovelBook { public OffNovelBook(String name, int price, String autor) { super(name, price, autor); } @Override public int getPrice() { int price=super.getPrice(); int oprice=0; if(price>4000){ oprice= price*90/100; }else{ oprice= price*80/100; } return oprice; } }
static { // 静态模块加载数据,实际项目一般由持久层完成 booklist.add(new NovelBook("巴黎圣母院", 3200, "雨果")); booklist.add(new NovelBook("悲惨世界", 5600, "雨果")); booklist.add(new NovelBook("天龙八部", 4800, "金庸")); booklist.add(new NovelBook("挪威的森林", 2200, "村上春树")); booklist.add(new OffNovelBook("唐诗三百首", 4500, "谁写的")); }
public interface IComputerBook extends IBook { public String getScope(); }
public class ComputerBook implements IComputerBook { private String name; private int price; private String autor; private String scope; public ComputerBook(String name, int price, String autor, String scope) { this.name = name; this.price = price; this.autor = autor; this.scope = scope; } public String getScope() { return this.scope; } public String getAuthor() { return this.autor; } public String getName() { return this.name; } public int getPrice() { return this.price; } }
static { // 静态模块加载数据,实际项目一般由持久层完成 booklist.add(new NovelBook("巴黎圣母院", 3200, "雨果")); booklist.add(new NovelBook("悲惨世界", 5600, "雨果")); booklist.add(new NovelBook("天龙八部", 4800, "金庸")); booklist.add(new NovelBook("挪威的森林", 2200, "村上春树")); booklist.add(new OffNovelBook("下架的书", 4500, "谁写的")); booklist.add(new ComputerBook("大数据入门", 8500, "李老师", "大数据")); booklist.add(new ComputerBook("嵌入式精髓", 2600, "吴老师", "嵌入式")); }
参考书籍《设计模式之禅》
我是菜鸟,我在路上。