本文主要是介绍1_开闭原则(Open Closed Principle),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
开闭原则(Open Closed Principle)
1.概念
开闭原则(Open-Closed Principle)是指一个软件实体如类、模块和函数应该对扩展开放, 对修改关闭。所谓的开闭,也正是对扩展和修改两个行为的一个原则。强调的是用抽象构建框架,用实现扩展细节。
2.案例演示与讲解
创建一个课程接口
public interface ICourse {Integer getId();String getName();Double getPrice();
}
创建一个课程的具体实现类
public class Course implements ICourse{private Integer id;private String name;private Double price;public JavaCourse(Integer id, String name, Double price) {this.id = id;this.name = name;this.price = price;}public Integer getId() {return this.id;}public String getName() {return this.name;}public Double getPrice() {return this.price;}
}
创建一个课程具体细节类(Java课程实现)来实现逻辑处理
public class JavaDiscountCourse extends Course {public JavaDiscountCourse(Integer id, String name, Double price) {super(id, name, price);}//假设双12活动,java课程打6折优惠逻辑处理public Double getDiscountPrice(){return super.getPrice() * 0.6;}
}public class VueDiscountCourse extends Course {public JavaDiscountCourse(Integer id, String name, Double price) {super(id, name, price);}//假设双12活动,vue课程打7折优惠逻辑处理public Double getDiscountPrice(){return super.getPrice() * 0.7;}
}
调用类实现功能
public class OpenCloseTest {public static void main(String[] args) {//创建一个java课程ICourse iCourse = new JavaDiscountCourse(1,"Java架构",11800D);JavaDiscountCourse discountCourse = (JavaDiscountCourse)iCourse;System.out.println("课程ID:" + discountCourse.getId() + "\n课程标题:《" + discountCourse.getName() + "》" +"\n原价:" + discountCourse.getPrice() + "\n售价:" + discountCourse.getDiscountPrice());//创建一个vue课程ICourse iCourse = new VueDiscountCourse(1,"vue课程",11800D);VueDiscountCourse discountCourse = (VueDiscountCourse)iCourse;System.out.println("课程ID:" + discountCourse.getId() + "\n课程标题:《" + discountCourse.getName() + "》" +"\n原价:" + discountCourse.getPrice() + "\n售价:" + discountCourse.getDiscountPrice());}
}
执行结果:
3.开闭原则类图:
4.开闭原则类图概念理解
创建一个接口和实现中抽象方法和实现,保持结构不变关闭的修改,
如果我们对实现类中的功能不满足,可以创建一个类继承实现类来扩展功能满足需要,应该对扩展开放。
java 代码实现
public interface Book{public String getName();//获取书名public double getPrice(); //获取价格
}
public class BookeImp implements Book {@Overridepublic String getName() {return "书";}@Overridepublic double getPrice() {return 10.0;}
}
public class JavaBook extends BookeImp {public String getName() {return "Java书";}public double getPrice() {return 100.0;}
}
public class Use {public static void main(String[] args) {//需求打印通用书名和价格Booke book = new BookeImp();System.out.println(book.getName());System.out.println(book.getPrice());//修改需求打印java书名和价格,保持原有抽象类和现实的结构修改关闭,扩展新的需求功能Booke javaBook = new JavaBook();System.out.println(javaBook.getName());System.out.println(javaBook.getPrice());}
}
这篇关于1_开闭原则(Open Closed Principle)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!