六大原则-开闭原则
2020-04-19 本文已影响0人
程序男保姆
开闭原则
-
定义: 一个软件实体如类,模块,和函数应该对扩展开放,对修改关闭。
-
用抽象构建框架,用实现扩展细节
-
优点: 提高软件系统的可复用性及可维护性
package com.design.principle.openclose;
/***
* 课程接口
*/
public interface ICourse{
/** 获取课程ID */
public Integer getId() ;
/** 获取课程名称 */
public String getName() ;
/** 获取课程价格 */
public Double getPrice() ;
}
package com.design.principle.openclose;
/***
* Java 课程
*/
public class JavaCourse implements ICourse {
/** 课程ID */
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;
}
@Override
public Integer getId() {
return id;
}
@Override
public String getName() {
return name;
}
@Override
public Double getPrice() {
return price;
}
@Override
public String toString() {
return "JavaCourse{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
'}';
}
}
package com.design.principle.openclose;
/***
* Flutter 课程
*/
public class FlutterCourse implements ICourse {
/** 课程ID */
private Integer id;
/** 课程名称 */
private String name;
/** 课程价格 */
private Double price;
public FlutterCourse(Integer id, String name, Double price) {
this.id = id;
this.name = name;
this.price = price;
}
@Override
public Integer getId() {
return id;
}
@Override
public String getName() {
return name;
}
@Override
public Double getPrice() {
return price;
}
@Override
public String toString() {
return "FlutterCourse{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
'}';
}
}
package com.design.principle.openclose;
/***
* Java 课程
*/
public class JavaCourseDiscount extends JavaCourse {
public JavaCourseDiscount(Integer id, String name, Double price) {
super(id, name, price);
}
/***
* 折扣后价格
* @return
*/
public Double getDiscountPrice() {
return super.getPrice()*0.8;
}
}
package com.design.principle.openclose;
public class Test {
public static void main(String[] args) {
// 1 获取Java课程的信息
ICourse course = new JavaCourse(1,"java",12.00);
System.out.println("Java课程id"+course.getId());
System.out.println("Java课程name"+course.getName());
System.out.println("Java课程price"+course.getPrice());
System.out.println();
System.out.println();
System.out.println();
// 要求只对Java课程的价格打8折
ICourse courseDiscount = new JavaCourseDiscount(1,"java",12.00);
JavaCourseDiscount javaCourseDiscount = (JavaCourseDiscount) courseDiscount;
System.out.println("Java课程id"+javaCourseDiscount.getId());
System.out.println("Java课程name"+javaCourseDiscount.getName());
System.out.println("Java课程price"+javaCourseDiscount.getPrice());
System.out.println("Java课程discountPrice"+javaCourseDiscount.getDiscountPrice());
}
}