设计的七大原则

单一职责原则

定义:不要存在多于一个导致类变更的原因(即一个类只负责一项职责。)
一个类/接口/方法只负责一项职责
优点:降低类的复杂度,提高类的可读性,提高系统的可维护性,降低变更引起的风险

问题代码

  1. public class SingleResponsibility {
  2. public static void main(String[] args) {
  3. Vehicle vehicle = new Vehicle();
  4. vehicle.run("摩托车");
  5. vehicle.run("骑车");
  6. vehicle.run("飞机");
  7. }
  8. }
  9. // 交通工具类
  10. class Vehicle {
  11. public void run(String vehicle) {
  12. System.out.println(vehicle + " 在公路上运行....");
  13. }
  14. }

问题:摩托车和骑车可以在公路上跑但是飞机不行 解决:让每个类的职责进行单一可以创建地上跑的类 天上飞的类和水里游的类但是每个类都进行区分导致类臃肿而且是没有必要的,所有可以进行写多个方法进行拆分,虽然没有在类这个级别上遵守单一职责原则,但是在方法级别上,仍然是遵守单一职责

修改后的代码

  1. public class SingleResponsibility {
  2. public static void main(String[] args) {
  3. Vehicle vehicle = new Vehicle();
  4. vehicle.run("摩托车");
  5. vehicle.runWater("船");
  6. vehicle.runAir("飞机");
  7. }
  8. }
  9. // 交通工具类
  10. class Vehicle {
  11. public void run(String vehicle) {
  12. System.out.println(vehicle + " 在公路上运行....");
  13. }
  14. public void runAir(String vehicle) {
  15. System.out.println(vehicle + " 在天空上运行....");
  16. }
  17. public void runWater(String vehicle) {
  18. System.out.println(vehicle + " 在水中行....");
  19. }
  20. }

依赖倒置原则

定义:高层模块不应该依赖底层模块,二者都应该依赖其抽象
抽象不应该依赖细节,细节应该依赖抽象
针对接口编程,不针对实现编程
优点:可以减少类间的耦合,提高系统稳定性,提高代码可读性和可维护性,降低修改程序造成的风险

问题代码

  1. public class OpenClose {
  2. public static void main(String[] args) {
  3. Graphical graphical = new Graphical();
  4. GraphicEditor graphicEditor = new GraphicEditor();
  5. graphicEditor.drawRectangle(graphical);
  6. }
  7. }
  8. //这是一个画图形类
  9. class GraphicEditor {
  10. //画矩形
  11. public void drawRectangle(Graphical graphical) {
  12. graphical.drawRectangle();
  13. }
  14. //绘制圆形
  15. public void drawCircle(Graphical graphical) {
  16. graphical.drawCircle();
  17. }
  18. //绘制三角形
  19. public void drawTriangle(Graphical graphical) {
  20. graphical.drawTriangle();
  21. }
  22. }
  23. //图形类
  24. class Graphical {
  25. //绘制矩形
  26. public void drawRectangle() {
  27. System.out.println(" 绘制矩形 ");
  28. }
  29. //绘制圆形
  30. public void drawCircle() {
  31. System.out.println(" 绘制圆形 ");
  32. }
  33. //绘制三角形
  34. public void drawTriangle() {
  35. System.out.println(" 绘制三角形 ");
  36. }
  37. }

问题:每次需要画一个新的图形都需要在图形中添加新的方法 解决:将图形类变成接口要画任何图形只需要创建一个类实现接口就可以了

修改后的代码

  1. public class OpenClose {
  2. public static void main(String[] args) {
  3. Graphical rectangle = new Rectangle();
  4. Graphical circular = new Circular();
  5. Graphical triangle = new Triangle();
  6. GraphicEditor graphicEditor = new GraphicEditor();
  7. graphicEditor.drawRectangle(rectangle);
  8. graphicEditor.drawRectangle(circular);
  9. graphicEditor.drawRectangle(triangle);
  10. }
  11. }
  12. //这是一个画图形类
  13. class GraphicEditor {
  14. //画图形
  15. public void drawRectangle(Graphical graphical) {
  16. graphical.draw();
  17. }
  18. }
  19. //图形类
  20. interface Graphical {
  21. //绘制图形
  22. void draw();
  23. }
  24. //矩形
  25. class Rectangle implements Graphical{
  26. @Override
  27. public void draw() {
  28. System.out.println("绘制矩形");
  29. }
  30. }
  31. //圆形
  32. class Circular implements Graphical{
  33. @Override
  34. public void draw() {
  35. System.out.println("绘制圆形");
  36. }
  37. }
  38. //三角形
  39. class Triangle implements Graphical{
  40. @Override
  41. public void draw() {
  42. System.out.println("绘制三角形");
  43. }
  44. }

接口隔离原则

定义:用多个专门的接口,而不适用单一的总接口,客户端不应该依赖他不需要的接口
优点:符合高内聚低耦合的设计思想,使得类具有很好的可读性,可扩展性和可维护性

问题代码

  1. public class InterfaceIsolation {
  2. public static void main(String[] args) {
  3. IAnimal iAnimal = new Dog();
  4. iAnimal.run();
  5. iAnimal.eat();
  6. }
  7. }
  8. //动物接口
  9. interface IAnimal{
  10. void run();
  11. void eat();
  12. void fly();
  13. }
  14. class Dog implements IAnimal{
  15. @Override
  16. public void run() {
  17. System.out.println("跑跑跑");
  18. }
  19. @Override
  20. public void eat() {
  21. System.out.println("吃吃吃");
  22. }
  23. @Override
  24. public void fly() {
  25. }
  26. }

问题:狗类继承了动物接口但是狗并不会飞 ,这就说明实现了不需要的接口方法 解决:将接口的功能尽可能细化,用到那个接口实现那个接口 但是一定要释放否则会造成接口太过庞大

修改后的代码

  1. public class InterfaceIsolation {
  2. public static void main(String[] args) {
  3. IAnimalBase iAnimal = new Dog();
  4. iAnimal.run();
  5. iAnimal.eat();
  6. }
  7. }
  8. //动物接口
  9. interface IAnimalBase{
  10. void run();
  11. void eat();
  12. }
  13. interface IAnimalSpecial{
  14. void fly();
  15. }
  16. class Dog implements IAnimalBase{
  17. @Override
  18. public void run() {
  19. System.out.println("跑跑跑");
  20. }
  21. @Override
  22. public void eat() {
  23. System.out.println("吃吃吃");
  24. }
  25. }
  26. //鸟是会飞了 可以实现基础的功能和他自己有的功能
  27. class Bird implements IAnimalBase,IAnimalSpecial{
  28. @Override
  29. public void run() {
  30. System.out.println("跑跑跑");
  31. }
  32. @Override
  33. public void eat() {
  34. System.out.println("吃吃吃");
  35. }
  36. @Override
  37. public void fly() {
  38. System.out.println("飞飞");
  39. }
  40. }

开闭原则

定义:一个软件实体如类、模块和函数应该对扩展开放,对修改关闭
用抽象构建框架,用实体实现细节
优点:提高软件系统的可复用性和可维护性

问题代码

public class OpenClose {
    public static void main(String[] args) {
        ICourse javaCourse = new JavaCourse();
        System.out.println("java课程的售价为" + javaCourse.getPrice());
        //课程打八折--需要在javaCoures中添加一个新的方法
        System.out.println("java课程8折售价"+javaCourse.getPrice0());
        //由于接口中没有这个方法所以获取不到 需要在接口中添加getPrice0方法才能调用
    }

}
//所有课程的接口
interface ICourse{
    double getPrice();
}
//java课程类
class JavaCourse implements ICourse {
    private double pirce = 100.0;

    @Override
    public double getPrice() {
        return pirce;
    }
    public double getPirce0(){
        return pirce*0.8;
    }
}

问题:打不同的折需要在接口中进行不同的修改扩展性不强需要一直修改底层代码 解决:创建一个java打折类继承java课程类 写一个方法只需要修改价格就可以了原价格也可以同时获取到对原数据不会进行改变 所以只是对原有类进行了扩展

修改后的代码

public class OpenClose {
    public static void main(String[] args) {
        ICourse iCourse = new JavaCourseDiscount();
        //获取课程只需要强制转换成JavaCourseDiscount就可以了
        JavaCourseDiscount   javaCourse = (JavaCourseDiscount) iCourse;
        System.out.println("java课程售价" + javaCourse.getPrice());
        //课程打八折--需要在javaCoures中添加一个新的方法
        System.out.println("java课程8折售价" + javaCourse.getPrice0());
    }

}

//所有课程的接口
interface ICourse {
    double getPrice();
}

//java课程类
class JavaCourse implements ICourse {
    private double pirce = 100.0;

    @Override
    public double getPrice() {
        return pirce;
    }


}
//课程打折类 继承javaCourse
class JavaCourseDiscount extends JavaCourse {

    public double getPrice0() {
        return super.getPrice()*0.8;
    }
}

迪米特法则

定义:一个对象应该对其他对象保持最少的了解,尽量降低类与类的耦合

  1. 迪米特法则还有个更简单的定义:只与直接的朋友通信
  2. 直接的朋友:每个对象都会与其他对象有耦合关系,只要两个对象之间有耦合关系, 我们就说这两个对象之间是朋友关系。耦合的方式很多,依赖,关联,组合,聚合 等。其中,我们称出现成员变量,方法参数,方法返回值中的类为直接的朋友,而 出现在局部变量中的类不是直接的朋友。也就是说,陌生的类最好不要以局部变量 的形式出现在类的内部。

优点:降低类直接耦合

问题代码

public class Dimitt {
    public static void main(String[] args) {
        Boss boss = new Boss();
        TeamLeader teamLeader = new TeamLeader();
        boss.commandCheckNumber(teamLeader);
    }
}

//老板类
class Boss {
    public void commandCheckNumber(TeamLeader teamLeader) {
        List<Course> courseList = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            courseList.add(new Course());
        }
        teamLeader.checkNumberOfCourse(courseList);
    }
}

//队长类
class TeamLeader {
    public void checkNumberOfCourse(List<Course> coursesLisr) {
        System.out.println(coursesLisr.size());
    }
}

//课程类
class Course {
    int count = 1;
}

老板让队长去查课程的数量 老板不应该和课程有任何关系所以不合理 解决:将和Course有关的内容放入队长类

修改后的代码

public class Dimitt {
    public static void main(String[] args) {
        Boss boss = new Boss();
        TeamLeader teamLeader = new TeamLeader();
        boss.commandCheckNumber(teamLeader);
    }
}

//老板类
class Boss {
    public void commandCheckNumber(TeamLeader teamLeader) {

        teamLeader.checkNumberOfCourse();
    }
}

//队长类
class TeamLeader {
    public void checkNumberOfCourse() {
        List<Course> courseList = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            courseList.add(new Course());
        }
        System.out.println(courseList.size());
    }
}

//课程类
class Course {
    int count = 1;
}

里氏替换原则

定义:在使用继承时,遵循里氏替换原则,在子类中尽量不要重写父类的方法
继承必须确保超类所有的性质在子类中依然成立

里氏替换原则告诉我们,继承实际上让两个类耦合性增强了,在适当的情况下,可 以通过聚合,组合,依赖 来解决问题

问题代码

public class RichterSubstitution {
    public static void main(String[] args) {
        A a = new A();
        System.out.println("11-3=" + a.func1(11, 3));
        System.out.println("1-8=" + a.func1(1, 8));
        System.out.println("-----------------------");
        B b = new B();
        System.out.println("11-3=" + b.func1(11, 3));//这里本意是求出11-3
        System.out.println("1-8=" + b.func1(1, 8));// 1-8
    }
}

class A{
    // 返回两个数的差
    public int func1(int num1, int num2) {
        return num1 - num2;
    }
}
class B extends A{
    //子类重写了父类的方法
    @Override
    public int func1(int num1, int num2) {
        return num1+num2;
    }
}

问题:本来是通过func1求减法的但是由于B对方法的重写导致结果错误 解决:通过合成和聚合的方法解决

修改后的代码

public class Liskov {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        A a = new A();
        System.out.println("11-3=" + a.func1(11, 3));
        System.out.println("1-8=" + a.func1(1, 8));

        System.out.println("-----------------------");
        B b = new B();
        //因为B类不再继承A类,因此调用者,不会再func1是求减法
        //调用完成的功能就会很明确
        System.out.println("11+3=" + b.func1(11, 3));//这里本意是求出11+3
        System.out.println("1+8=" + b.func1(1, 8));// 1+8
        System.out.println("11+3+9=" + b.func2(11, 3));        
        //使用组合仍然可以使用到A类相关方法
        System.out.println("11-3=" + b.func3(11, 3));// 这里本意是求出11-3
    }

}

//创建一个更加基础的基类
class Base {
    //把更加基础的方法和成员写到Base类
}

// A类
class A extends Base {
    // 返回两个数的差
    public int func1(int num1, int num2) {
        return num1 - num2;
    }
}
// B类继承了A
// 增加了一个新功能:完成两个数相加,然后和9求和
class B extends Base {
    //如果B需要使用A类的方法,使用组合关系
    private A a = new A();

    //这里,重写了A类的方法, 可能是无意识
    public int func1(int a, int b) {
        return a + b;
    }

    public int func2(int a, int b) {
        return func1(a, b) + 9;
    }

    //我们仍然想使用A的方法
    public int func3(int a, int b) {
        return this.a.func1(a, b);
    }
}

合成/复用原则

定义:尽量使用合成或者聚合的方式而不是继承
原则是尽量使用合成(一个对象创建后,另一个对象同时创建好了)/聚合(set方法)的方式,而不是使用继承—>对里式替换原则的说法
单一职责:每个类的功能尽量负责一个功能—由于怕类的臃肿可以变成方法职责单一
依赖倒置:根据接口进行编程
接口隔离:接口尽量细化—同时也要要适度
开闭原则:要保持可扩展性
迪米特法则:只和熟悉的交流
里氏替换:不要使用继承
合成复用原则:尽量使用组合/聚合