编写软件过程中,程序员面临着来自耦合性,内聚性以及可维护性,可扩展性,重用性,灵活性等多方面的挑战,设计模式是为了让程序(软件),具有更好的代码重用性、可读性、可扩展性、可靠性,使程序呈现高内聚,低耦合的特性。

  1. 代码重用性(相同功能的代码,不用多次编写)
  2. 可读性(编程规范性,便于理解)
  3. 可扩展性(需要增加新功能,非常的方便)
  4. 可靠性(增加新的功能后,对原有的功能不影响)
  5. 高内聚(模块内部非常紧密)、低耦合(功能之间依赖性低)

设计模式包含了面向对象的精髓,“懂了设计模式,你就懂了面向对象分析和设计(OOA/D)的精要”

设计模式原则,其实就是程序员在编程时,应当遵守的原则,也是各种设计模式的基础(即:设计模式为什么这样设计的依据)。

设计模式常见的六大原则有:

  1. 单一职责原则
  2. 接口隔离原则
  3. 依赖倒转(倒置)原则
  4. 里氏替换原则
  5. 开闭原则
  6. 迪米特法则

单一职责原则

约定大于编码,所有的设计模式都需要遵循这 7 种原则。

对类来说的,即一个类应该只负责一项职责。如类 A 负责两个不同职责:职责1,职责2。当职责 1 需求变更而改变 A 时,可能造成职责 2 执行错误,所以需要将类A的粒度分解为 A1,A2。

例子

交通工具案例。

方式 1

所有的交通工具在一个方法上面跑。

class Vehicle {
	public void run(String vehicle){
		System.out.println(vehicle + "在公路上跑....");
    }
    public static void main(String[] args) {
       	Vehicle vehicle = new Vehicle();
       	vehicle.run("汽车");
        vehicle.run("飞机");
        vehicle.run("游艇");
    }
}

程序运行:

汽车在公路上跑....
飞机在公路上跑....
游艇在公路上跑....

有没有发现一个问题,飞机和游艇都在公路上跑,游艇在公路上跑。发现有问题了,那就改改代码吧。

class Vehicle {
	public void run(String vehicle){
		if("汽车".equals(vehicle)) {
			System.out.println(vehicle + "在公路上跑....");
		}
        else if("飞机".equals(vehicle)) {
			System.out.println(vehicle + "在天空飞....");
		}
        else if("游艇".equals(vehicle)) {
			System.out.println(vehicle + "在水中划....");
		}
    }
    public static void main(String[] args) {
       	Vehicle vehicle = new Vehicle();
       	vehicle.run("汽车");
        vehicle.run("飞机");
        vehicle.run("游艇");
    }
}

程序运行:

汽车在公路上跑....
飞机在在天空飞....
游艇在水中划....

现在似乎没什么问题了,但是这违反了单一职责原则,而且代码的重用性、可读性、可扩展性、可靠性都比较差。解决的方法根据交通工具运行方法不同,分解成不同类即可。

方式 2

分解成三种交通工具类

class RoadVehicle {
	public void run(String vehicle){
		System.out.println(vehiclc + "在公路上跑....");
	}
}

class AirVehicle {
	public void run(String vchiclc){
		Systcm.out.println(vchicle + "在天空上飞...");
    }
}
                           
class WatcrVchiclc {
    public void run(String vehicle){
        System.out.println(vehicle + "在水中划....");
    }
}

public class Main {
    public static void main(String[] args) {
       	RoadVehicle roadVehicle = new RoadVehicle();
       	roadVehicle.run("汽车");
        
        AirVehicle airVehicle = new AirVehicle();
        airVehicle.run("飞机");
        
        WaterVehicle waterVehicle = new WaterVehicle();
        waterVehicle.run("游艇");
    }
}

遵守类级别的单一职责原则。

类级别的单一职责原则是最好的,也是最彻底的。但是在本案例中代码简单,方法就只有一个,若要对类这个级别中遵守单一职责,改动较大,可以降为方法级别的单一职责,参见方案 3。

方式 3

一个类中分别有三种交通工具不同运作的方式。

class Vehicle {
    public void run(String vehicle) {
		System.out.println(vehicle + "在公路上跑....");
    }
    
    public void runAir(String vchiclc){
        Systcm.out.println(vehiclc + "在天空上飞...");
    }
    
    public void runWater(String vehicle) {
    	System.out.printIn(vehicle + "在水中划....");
    }
    public static void main(String[] args) {
       	Vehicle vehicle = new Vehicle();
       	vehicle.run("汽车");
        vehicle.runAir("飞机");
        vehicle.runWatetr("游艇");
    }
}

遵守方法级别的单一职责原则。

这种修改方法没有对原来的类做大的修改,只是增加方法。这里虽然没有在类这个级别上遵守单一职责原则,但是在方法级别上,仍然是遵守单一职责。

注意:方法级别的单一职责只是类中的模块或者功能较少的时候可以这么做,否则直接建议使用类级别的单一职责原则。

接口隔离原则

客户端不应该依赖它不需要的接口,即一个类对另一个类的依赖应孩建立在最小的接口上。最小接口,其实就是将接口中用不到的方法,将大的接口(抽象方法多的)拆分成小的接口(抽象方法少的)。若要实现某个方法,只需要实现即可。

请看此类图的关系。

image-20220402144032636

对应的代码如下所示

public class Segregation1 {

    public static void main(String[] args) {
        A a = new A();
        a.depend1(new B());
        a.depend2(new B());
        a.depend3(new B());

        C c = new C();
        c.depend1(new D());
        c.depend4(new D());
        c.depend5(new D());
    }

}

interface Interface1 {
    void operation1();
    void operation2();
    void operation3();
    void operation4();
    void operation5();
}

/**
 * B 实现类
 */
class B implements Interface1 {

    @Override
    public void operation1() {
        System.out.println("B 实现 operation1");
    }

    @Override
    public void operation2() {
        System.out.println("B 实现 operation2");
    }

    @Override
    public void operation3() {
        System.out.println("B 实现 operation3");
    }

    @Override
    public void operation4() {
        System.out.println("B 实现 operation4");
    }

    @Override
    public void operation5() {
        System.out.println("B 实现 operation5");
    }
}

/**
 * D 实现类
 */
class D implements Interface1 {

    @Override
    public void operation1() {
        System.out.println("D 实现 operation1");
    }

    @Override
    public void operation2() {
        System.out.println("D 实现 operation2");
    }

    @Override
    public void operation3() {
        System.out.println("D 实现 operation3");
    }

    @Override
    public void operation4() {
        System.out.println("D 实现 operation4");
    }

    @Override
    public void operation5() {
        System.out.println("D 实现 operation5");
    }
}

/**
 * 类 A 中,只依赖了接口的 operation1()、operation2()、operation3() 方法
 */
class A {
    public void depend1(Interface1 i) {
        i.operation1();
    }

    public void depend2(Interface1 i) {
        i.operation2();
    }

    public void depend3(Interface1 i) {
        i.operation3();
    }
}

/**
 * 类 C 中,只依赖了接口的 operation1()、operation4()、operation5() 方法
 */
class C {
    public void depend1(Interface1 i) {
        i.operation1();
    }

    public void depend4(Interface1 i) {
        i.operation4();
    }

    public void depend5(Interface1 i) {
        i.operation5();
    }
}

A 只依赖了接口的 operation1()、operation2()、operation3() 方法,operation4()、operation5() 方法没有使用到,C 只依赖了接口的 operation1()、operation4()、operation5() 方法,operation2()、operation3() 方法没有使用到。没有使用的方法显得多余,所以就违背了接口隔离的原则。

此时我们需要对接口进行拆分,拆分之后的代码如下所示。

package top.bestguo.segregation.after;

public class Segregation1 {

    public static void main(String[] args) {
        A a = new A();
        a.depend1(new B());
        a.depend2(new B());
        a.depend3(new B());

        C c = new C();
        c.depend1(new D());
        c.depend4(new D());
        c.depend5(new D());
    }

}

interface Interface1 {
    void operation1();
}

interface Interface2 {
    void operation2();
    void operation3();
}

interface Interface3 {
    void operation4();
    void operation5();
}

/**
 * B 实现类
 */
class B implements Interface1, Interface2 {

    @Override
    public void operation1() {
        System.out.println("B 实现 operation1");
    }

    @Override
    public void operation2() {
        System.out.println("B 实现 operation2");
    }

    @Override
    public void operation3() {
        System.out.println("B 实现 operation3");
    }
}

/**
 * D 实现类
 */
class D implements Interface1, Interface3 {

    @Override
    public void operation1() {
        System.out.println("D 实现 operation1");
    }

    @Override
    public void operation4() {
        System.out.println("D 实现 operation4");
    }

    @Override
    public void operation5() {
        System.out.println("D 实现 operation5");
    }
}

/**
 * 类 A 中,只依赖了接口的 operation1()、operation2()、operation3() 方法
 */
class A {
    public void depend1(Interface1 i) {
        i.operation1();
    }

    public void depend2(Interface2 i) {
        i.operation2();
    }

    public void depend3(Interface2 i) {
        i.operation3();
    }
}

/**
 * 类 C 中,只依赖了接口的 operation1()、operation4()、operation5() 方法
 */
class C {
    public void depend1(Interface1 i) {
        i.operation1();
    }

    public void depend4(Interface3 i) {
        i.operation4();
    }

    public void depend5(Interface3 i) {
        i.operation5();
    }
}

然后对应的类图如下所示,这样一来就对接口进行了分离,该用到的方法都用到了。也不会显得特别的多余了。

image-20220402144907003

依赖倒置原则

  1. 高层模块不应该依赖低层模块,二者都应该依赖其抽象。
  2. 抽象不应该依赖细节,细节应该依赖抽象。
  3. 依赖倒置的中心思想是面向接口编程。
  4. 依赖倒转原则是基于这样的设计理念:相对于细节的多变性,抽象的东西要稳定的多。以抽象为基础搭建的架构比以细节为基础的架构要稳定的多。在 Java 中,抽象指的是接口或抽象类,细节就是具体的实现类。
  5. 使用接口或抽象类的目的是制定好规范,而不涉及任何具体的操作,把展现细节的任务交给他们的实现类去完成。

例子

完成 Person 接收消息的功能。

public class Inversion1 {

    public static void main(String[] args) {
        Person person = new Person();
        person.getMessage(new Email());
    }

}

class Email {
    public String getInfo() {
        return "接收到消息:hello email!";
    }
}

class Person {
    public void getMessage(Email email) {
        System.out.println(email.getInfo());
    }
}

功能虽然实现了,但是如果我们获取的对象是微信,短信等等,则新增类,同时 Person 也要增加相应的接收方法。

解决思路:引入一个抽象的接口 IReceiver,表示接收者,这样Person类与接口 IReceiver 发生因为Email,WeiXin 等等属于接收的范围,他们各自实观 IReceiver 接口就ok,这样我们就符合依赖倒转原则。

public class Inversion2 {

    public static void main(String[] args) {
        Person person = new Person();
        person.getMessage(new Email());
    }

}

interface IReceiver {
    String getInfo();
}

class Email implements IReceiver {

    @Override
    public String getInfo() {
        return "接收到消息:hello email!";
    }
}

class Person {
    public void getMessage(IReceiver receiver) {
        System.out.println(receiver.getInfo());
    }
}

如果我们加一个微信的消息会怎么样?

class WeiXin implements IReceiver {

    @Override
    public String getInfo() {
        return "接收到微信消息:hello wechat!";
    }
}

public class Inversion2 {

    public static void main(String[] args) {
        Person person = new Person();
        person.getMessage(new Email());
        person.getMessage(new WeiXin());
    }
}

Person 类中不需要任何的改动,就实现了接收微信的消息,仅需实现该接口,在主方法中调用该类即可。

依赖倒转的其它三种形式

通过接口的方式实现

ITV 是电视的接口类,IOpenAndClose 是遥控器的接口类。实现遥控器的接口,再通过依赖的形式操作电视。

interface IOpenAndClose {
	public void open(iTv tv); //抽象方法,接收接口
}

interface ITV { // ITV接口
    public void play();
}

// 实现接口
class OpenAndClose implements IOpenAndClose {
    public void open(ITV tv){
		tv.play();
    }
}

通过构造方法

// 实现接口
class OpenAndClose implements IOpenAndClose {
    
    private ITV itv;
    
    public OpenAndClose(ITV itv) {
        this.itv = itv;
    }
    
    public void open(ITV tv){
		tv.play();
    }
}

通过 setter 方法

// 实现接口
class OpenAndClose implements IOpenAndClose {
    
    private ITV itv;
    
    public void setItv(ITV itv) {
        this.itv = itv;
    }
    
    public void open(ITV tv){
		tv.play();
    }
}

注意

  1. 低层模块尽量都要有抽象类或接口,或者两者都有,程序稳定性更好。
  2. 变量的声明类型尽量是抽象类或接口,这样我们的变量引用和实际对象间,就存在一个缓冲层,利于程序扩展和优化。
  3. 继承时遵循里氏替换原则。

里氏替换原则

继承包含这样一层含义:父类中凡是已经实现好的方法,实际上是在设定规范和契约,虽然它不强制要求所有的子类必须遵循这些契约,但是如果子类对这些已经实现的方法任意修改,就会对整个继承体系造成破坏。

继承在给程序设计带来便利的同时,也带来了弊端。比如使用继承会给程序带来侵入性,程序的可移植性降低,增加对象间的耦合性,如果一个类被其他的类所继承,则当这个类需要修改时,必须考虑到所有的子类,并且父类修改后,所有涉及到子类的功能都有可能产生故障。

  1. 里氏替换原则(Liskov Substitution Principle)在1988年,由麻省理工学院的以为姓里的女士提出的。
  2. 如果对每个类型为 T1 的对象 o1,都有类型为 T2 的对象o2,使得以 T1 定义的所有程序 P 在所有的对象 o1 都代换成 o2 时,程序 P 的行为没有发生变化,那么类型 T2 是类型 T1 的子类型。换句话说,所有引用基类的地方必须能透明地使用其子类的对象。
  3. 在使用继承时,遵循里氏替换原则,在子类中改变父类的原有功能时,最好不要重写父类的方法。
  4. 里氏替换原则告诉我们,继承实际上让两个类耦合性增强了,在适当的情况下,可以通过聚合,组合,依赖来解决问题

例子

class A {
    public int func1(int num1, int num2) {
        return num1 - num2;
    }
}

class B extends A {
    public int func1(int a, int b) {
        return a + b;
    }
    public int func2(int a, int b) {
        return func1(a, b) + 9;
    }
}
class Main {
    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));
        System.out.println("1-8=" + b.func1(1, 8));
        System.out.println("11+3+9=" + b.func2(11, 3));
    }
}

我们发现原来运行正常的相减功能发生了错误。原因就是类 B 无意中重写了父类的方法,造成原有功能出现错误。在实际编程中,我们常常会通过重写父类的方法完成新的功能,这样写起来虽然简单,但整个继承体系的复用性会比较差。特别是运行多态比较频繁的时候。

通用的做法是:原来的父类和子类都继承一个更通俗的基类,原有的继承关系去掉,采用依赖,聚合,组合等关系代替。

改进

// 需要有一个更加基础的类(抽象类,接口类也可以)
interface Base {
    public int func1(int num1, int num2);
}

class A implements Base {

    @Override
    public int func1(int num1, int num2) {
        return num1 - num2;
    }
}

class B implements Base {

    // 如果需要使用 A 方法,则使用组合关系。
    private A a = new A();

    @Override
    public int func1(int a, int b) {
        return a + b;
    }
    public int func2(int a, int b) {
        return func1(a, b) + 9;
    }
    public int func3(int a, int b) {
        return this.a.func1(a, b);
    }
}

class Main {

    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();
        // B 类不再继承自 A 类,所以调用者不会在认为func1是减法的操作了。在调用完成的功能会很明确。
        System.out.println("11+3=" + b.func1(11,3));
        System.out.println("1-8=" + b.func1(1, 8));
        System.out.println("11+3+9=" + b.func2(11, 3));
        // 使用组合方法可以使用到 A 类的相关方法。
        System.out.println("11-3=" + b.func3(11,3)); // 11-3=8
    }

}

开闭原则

  1. 开闭原则(Open Closed Principle)是编程中最基础、最重要的设计原则。
  2. 一个软件实体如类,模块和函数应该对扩展开放(对提供方),对修改关闭(对使用方)。用抽象构建框架,用实现扩展细节。
  3. 当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有的代码来实现变化。
  4. 编程中遵循其它原则,以及使用设计模式的目的就是遵循开闭原则。

例子

// 使用方
class GraphicEditor {
    // 接牧Shape对象,然后根据type,来绘制不同的图形
    public void drawShape(Shape s) {
        if (s.m_type == 1)
            drawRectangle(s);
        else if (s.m_type == 2)
            drawCircle(s);
    }

    public void drawRectangle(Shape r) {
        System.out.println("绘制矩形");
    }

    public void drawCircle(Shape r) {
        System.out.println("绘制圆形");
    }
}

class Shape {
    int m_type;
}

class Rectangle extends Shape {
    Rectangle() {
        super.m_type = 1;
    }
}

class Circle extends Shape {
    Circle() {
        super.m_type = 2;
    }
}

class Main {

    public static void main(String[] args) {
        GraphicEditor graphicEditor = new GraphicEditor();
        graphicEditor.drawShape(new Rectangle());
        graphicEditor.drawShape(new Circle());
    }

}

如果此时再添加一个三角形的类,创建一个三角形的类是有必要的,同时再使用方也要添加判断和方法。这就不符合开闭原则了。

class Triangle extends Shape {
    Triangle() {
        super.m_type = 3;
    }
}

// 使用方
class GraphicEditor {
    // 接牧Shape对象,然后根据type,来绘制不同的图形
    // 这里修改了
    public void drawShape(Shape s) {
        if (s.m_type == 1)
            drawRectangle(s);
        else if (s.m_type == 2)
            drawCircle(s);
        else if (s.m_type == 3)
            drawTriangle(s);
    }

    ......
	// 这里添加了新方法
    public void drawTriangle(Shape r) {
        System.out.println("绘制三角形");
    }
}

改进

改进办法就是给 Shape 类变成抽象来并提供 draw 这个抽象方法,让继承该抽象类的实现类实现该方法。使用方只需要调用 Shape 中提供的 draw 方法即可完成绘制。

abstract class Shape {
    int m_type;
    public abstract void draw();
}

class Circle extends Shape {
    Circle() {
        super.m_type = 1;
    }

    @Override
    public void draw() {
        System.out.println("绘制圆形");
    }
}

class Rectangle extends Shape {
    Rectangle() {
        super.m_type = 2;
    }

    @Override
    public void draw() {
        System.out.println("绘制矩形");
    }
}

class GraphicEditor {
    // 接牧Shape对象,然后根据type,来绘制不同的图形
    public void drawShape(Shape s) {
        s.draw();
    }
}

class Main {

    public static void main(String[] args) {
        GraphicEditor graphicEditor = new GraphicEditor();
        graphicEditor.drawShape(new Rectangle());
        graphicEditor.drawShape(new Circle());
    }

}

迪米特法则

  1. 一个对象应该对其他对象保持最少的了解。
  2. 类与类关系越密切,耦合度越大。
  3. 迪米特法则(Demeter Principle)又叫最少知道原则,即一个类对自己依赖的类知道的越少越好。也就是说,对于被依赖的类不管多么复杂,都尽量将逻辑封装在类的内部。对外除了提供的public方法,不对外泄露任何信息。
  4. 迪米特法则还有个更简单的定义:只与直接的朋友通信。
  5. 直接的朋友:每个对象都会与其他对象由耦合关系,只要两个对象之间有耦合关系,我们就说这两个对象之间是朋友关系。耦合的方式很多,依赖,关联,组合,聚合等。其中,我们称出现成员变量,方法参数,方法返回值中的类为直接的朋友,而出现在局部变量中的类不是直接的朋友。也就是说,陌生的类最好不要以局部变量的形式出现在类的内部。

例子

class Employee {
    private String id;
    public void setId(String id) {
        this.id = id;
    }
    public String getId() {
        return id;
    }
}

class CollegeEmployee {
    private String id;
    public void setId(String id) {
        this.id = id;
    }
    public String getId() {
        return id;
    }
}

// 学院员工类
class CollegeManager {
    public List<CollegeEmployee> getAllEmployee() {
        List<CollegeEmployee> list = new ArrayList<CollegeEmployee>();
        for (int i = 0; i < 10; i++) {
            CollegeEmployee emp = new CollegeEmployee();
            emp.setId("学院员工id= " +i);
            list.add(emp);
        }
        return list;
    }
}

// 学校管理类
class SchoolManager {
    //返回学校总部的员工
    public List<Employee> getAllEmployee() {
        List<Employee> list = new ArrayList<Employee>();
        for (int i = 0; i < 5; i++) {
            Employee emp = new Employee();emp.setId("学校总部员工id=" +i);
            list.add(emp);
        }
        return list;
    }

    void printAllEmployee(CollegeManager sub) {
        List<CollegeEmployee> list1 = sub.getAllEmployee();
        System.out.println("------------学院员工------------");
        for (CollegeEmployee e : list1) {
            System.out.println(e.getId());
        }
        List<Employee> list2 = this.getAllEmployee();
        System.out.println("------------学校总部员工----");
        for (Employee e : list2) {
            System.out.println(e.getId());
        }
    }
}

public class Main {

    public static void main(String[] args) {
        SchoolManager schoolManager = new SchoolManager();
        schoolManager.printAllEmployee(new CollegeManager());
    }

}

分析 SchoolManager 类的直接朋友类有哪些?其中 Employee、CollegeManager 是直接朋友关系。但是CollegeEmployee 类不是直接朋友关系,因为在成员变量,参数,方法返回值没有出现,而在局部变量中突然出现。它就是一个陌生类,这违背了迪米特法则。

改进

将输出学院的员工方法,封装到 CollegeManager。也就是员工管理相关的类不要出现在别的类里面。

class Employee {
    private String id;
    public void setId(String id) {
        this.id = id;
    }
    public String getId() {
        return id;
    }
}

class CollegeEmployee {
    private String id;
    public void setId(String id) {
        this.id = id;
    }
    public String getId() {
        return id;
    }
}

// 学院员工类
class CollegeManager {
    public List<CollegeEmployee> getAllEmployee() {
        List<CollegeEmployee> list = new ArrayList<CollegeEmployee>();
        for (int i = 0; i < 10; i++) {
            CollegeEmployee emp = new CollegeEmployee();
            emp.setId("学院员工id= " +i);
            list.add(emp);
        }
        return list;
    }
}

// 学校管理类
class SchoolManager {
    //返回学校总部的员工
    public List<Employee> getAllEmployee() {
        List<Employee> list = new ArrayList<Employee>();
        for (int i = 0; i < 5; i++) {
            Employee emp = new Employee();emp.setId("学校总部员工id=" +i);
            list.add(emp);
        }
        return list;
    }

    void printAllEmployee(CollegeManager sub) {
        List<CollegeEmployee> list1 = sub.getAllEmployee();
        System.out.println("------------学院员工------------");
        for (CollegeEmployee e : list1) {
            System.out.println(e.getId());
        }
        List<Employee> list2 = this.getAllEmployee();
        System.out.println("------------学校总部员工----");
        for (Employee e : list2) {
            System.out.println(e.getId());
        }
    }
}

public class Main {

    public static void main(String[] args) {
        SchoolManager schoolManager = new SchoolManager();
        schoolManager.printAllEmployee(new CollegeManager());
    }

}

迪米特法则的核心是降低类之间的耦合。

但是注意:由于每个类都减少了不必要的依赖,因此迪米特法则只是要求降低类间(对象间)耦合关系,并不是要求完全没有依赖关系。