设计模式之开闭原则

开放封闭原则(Open Close Principle,简称OCP)尽可能经过扩展软件实体的行为来实现变化,而不是经过修改已有的代码来实现变化ide

原始定义:Software entities (classes, modules, functions) should be open for extension but closed for modification。this

核心思想: 尽可能经过扩展软件实体来解决需求变化,而不是经过修改已有的代码来完成变化spa

通俗来说: 一个软件产品在生命周期内,都会发生变化,既然变化是一个既定的事实,咱们就应该在设计的时候尽可能适应这些变化,以提升项目的稳定性和灵活性设计

 

好比如今圣诞节,搞活动打折,有如下几种作法:code

1.新增打折接口blog

2.修改原油NewBook类接口

3.新增打折书籍类生命周期

按照开放扩展关闭修改原则,应该是第三种方案,这样原有代码不会受到修改。ip

//书籍接口
public
interface IBook { String getBookName(); String getAuthor(); int getPrice(); } //书籍类 public class NewBook implements IBook { private String bookName; private String author; private int price; public NewBook(String bookName, String author, int price){ this.bookName = bookName; this.author = author; this.price = price; } @Override public String getBookName() { return this.bookName; } @Override public String getAuthor() { return this.author; } @Override public int getPrice() { return this.price; } } //打折书籍类 public class OffBook extends NewBook { public OffBook(String bookName, String author, int price) { super(bookName, author, price); } public Double getPrice2(){ return this.getPrice()*0.7; } }
相关文章
相关标签/搜索