软件设计中的六大原则-开闭原则

设计模式六大原则:单一职责原则

设计模式六大原则:接口隔离原则

设计模式六大原则:依赖倒置原则

设计模式六大原则:里氏替换原则

设计模式六大原则:迪米特法则
 
设计模式六大原则:开闭原则
 
设计模式六大原则:开闭原则开闭原则(Open Close Principle):
Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

软件设计的过程中对于软件对象如:类,模块和方法等,应该遵守可以(开放)扩展,但是不允许(关闭)修改原则。

而开闭原则是六大设计原则的基础,是其他另外五个设计原则必须遵守的一个基本原则。

那么我们如何实现一个开闭原则呢?show code

首先定义一个接口,因为接口也有继承性,定义的时候定义一个接口对象就可以操作其实现类的所有操作。

package com.jackray.springbootdemo.service;

public interface ICourse {
    public String getCourseName();
    public String getCourseCode();
    public Double getCoursePrice();
}

定义一个dao实现了上面的接口

package com.jackray.springbootdemo.dao;

import com.jackray.springbootdemo.service.ICourse;

public class Course implements ICourse {
    private String name;
    private String code;
    private Double price;

    public Course(String name, String code, Double price) {
        this.name = name;
        this.code = code;
        this.price = price;
    }

    @Override
    public String getCourseName() {
        return this.name;
    }

    @Override
    public String getCourseCode() {
        return this.code;
    }

    @Override
    public Double getCoursePrice() {
        return this.price;
    }
}

实现一个打折的类继承原来的dao类和接口,在不不修改原来的类的基础之上,进行新功能的增加。

package com.jackray.springbootdemo.service;

import com.jackray.springbootdemo.dao.Course;

public class OPenCourse extends Course {

    public OPenCourse(String name, String code, Double price) {
        super(name, code, price);
    }

    public Double discountPrice(){
        return super.getCoursePrice() * 0.8;
    }
}

测试,不修改原来的类的基础上,实现了打折服务。

    public static void main(String[] args) {
        ICourse iCourse = new OPenCourse("java","001",100.00);
        System.out.println("打折前价格:"+iCourse.getCoursePrice()+"  打折后价格:"+((OPenCourse) iCourse).discountPrice());
    }

测试结果拿到了原来的价格和打折之后的价格。

打折前价格:100.0  打折后价格:80.0

大概如此,这里仅仅是一个开闭原则基本demo,这样的设计在工作的时虽然简单但是为程序提供了很好扩展性。

猜你喜欢

转载自blog.csdn.net/ppwwp/article/details/107589406