图解Java设计模式学习笔记——简介、七大原则、UML类图

一、设计模式简介

1、设计模式目的

编写软件过程中,程序员面临着来自耦合性、内聚性以及可维护性、可扩展性、重用性、

灵活性 等多方面的挑战,设计模式是为了让程序(软件)具有更好

  • 代码重用性:即相同功能的代码,不用多次编写
  • 可读性:即编程规范,便于其他程序员的阅读和理解
  • 可扩展性:即当需要新的功能时,非常的方便
  • 可靠性:即当我们增加新的功能后,对原来的功能没有影响
  • 使程序呈现高内聚、低耦合的特性

分析金句

  • 设计模式包含了面向对象的精髓,“懂了设计模式,你就懂了面向对象分析和设计的精要”。
  • Scott Mayers 在其巨著《Effective C++》曾经说过:C++ 老手和 C++ 新生的区别就是前者手背上有很多伤疤。

2、设计模式的七大原则

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

设计模式常用的七大原则有:

  • 单一职责原则
  • 接口隔离原则
  • 依赖倒转(倒置)原则
  • 里式替换原则
  • 开闭原则
  • 迪米特原则
  • 合成复用原则

二、设计模式七大原则

1、单一职责原理

1.1基本介绍

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

1.2应用实例

我们以交通工具为案例进行讲解。

方案一

public class SingleResponsibility1 {
    public static void main(String[] args) {
        Vehicle vehicle = new Vehicle();
        vehicle.run("摩托");
        vehicle.run("汽车");
        vehicle.run("飞机");
    }
}

class Vehicle {
    public void run(String vehicle){
        System.out.println(vehicle + " 在公路上运行...");
    }
}

方案一分析:在方案1的run方法中,违反了单一职责原则,一个交通工具做了很多事情。

方案二

根据交通工具运行方法不同,分解成不同类即可。

public class SingleResponsibility2 {
    public static void main(String[] args) {
        RoadVehicle readVehicle = new RoadVehicle();
        readVehicle.run("摩托车");
        readVehicle.run("汽车");
        AirVehicle airVehicle = new AirVehicle();
        airVehicle.run("飞机");
        WaterVehicle waterVehicle = new WaterVehicle();
        waterVehicle.run("轮船");
    }
}

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

class AirVehicle{
    public void run(String vehicle){
        System.out.println(vehicle + " 在天空上运行...");
    }
}

class WaterVehicle{
    public void run(String vehicle){
        System.out.println(vehicle + " 在水中运行...");
    }
}

方案2分析 :遵守单一职责原则。但是这样改动大,即将类分解,同时要修改客户端。

方案三

直接修改Vehicle类,改动的代码会比较少

public class SingleResponsibility1 {
    public static void main(String[] args) {
        Vehicle vehicle = new Vehicle();
        vehicle.run("汽车");
        vehicle.runAir("飞机");
        vehicle.runWater("轮船");
    }
}

class Vehicle {
    public void run(String vehicle){
        System.out.println(vehicle + " 在公路上运行...");
    }

    public void runAir(String vehicle){
        System.out.println(vehicle + " 在天空运行...");
    }

    public void runWater(String vehicle){
        System.out.println(vehicle + " 在水中运行...");
    }
}

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

1.3总结

单一职责原则注意事项和细节:

  • 降低类的复杂度,一个类只负责一个职责。
  • 提高类的可读性,可维护性。
  • 降低变更引起的风险。
  • 通常情况下,我们应该遵守单一职责原则只有逻辑足够简单,才可以在代码级违反单一原则(只有类的方法足够少,可以在方法级别保持单一原则)。

2、接口隔离原则

2.1 基本介绍

客户端不应该依赖它不需要的借口,即一个类对另一个类的依赖应该简历在最小的接口上。

看下图,它我违反了接口隔离原则。

  •  类A通过接口 Interface1 依赖B类,类C通过接口 Interface1 依赖类D,如果 Interface1 对于 类A 和 类C 来说不是最小接口,那么 类B和类C必须去实现他们不需要的方法
  • 按接口隔离原则应该这样处理:将接口 Interface1 拆分成独立的几个接口(这里我们拆分成3个接口),类 A 和 类C 分别与他们依赖的接口简历依赖关系,也就是采用接口隔离原则

2.2 应用实例1(按照上述类图)

package org.example.segtration;

public class Segregation1 {
    public static void main(String[] args) {

    }
}

/**
 * Interface1 接口
 */
interface Interface1 {
    void operation1();
    void operation2();
    void operation3();
    void operation4();
    void operation5();
}

/**
 * 类B实现 Interface1 接口,其中 operation4、operation5,其实是不需要实现的方法
 */
class B implements Interface1{

    public void operation1() {
        System.out.println("B 实现了 operation1");
    }
    public void operation2() {
        System.out.println("B 实现了 operation2");
    }
    public void operation3() {
        System.out.println("B 实现了 operation3");
    }
    public void operation4() {
        System.out.println("B 实现了 operation4");
    }
    public void operation5() {
        System.out.println("B 实现了 operation5");
    }
}

/**
 * 类C实现 Interface1 接口,其中 operation2、operation3,其实是不需要实现的方法
 */
class D implements Interface1{

    public void operation1() {
        System.out.println("D 实现了 operation1");
    }
    public void operation2() {
        System.out.println("D 实现了 operation2");
    }
    public void operation3() {
        System.out.println("D 实现了 operation3");
    }
    public void operation4() {
        System.out.println("D 实现了 operation4");
    }
    public void operation5() {
        System.out.println("D 实现了 operation5");
    }
}

/**
 * A 类通过接口Interface1 依赖(使用)B类,但是只会用到1,2,3方法
 */
class A {
    public void depend1(Interface1 interface1) {
        interface1.operation1();
    }

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

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

/**
 * C 类通过接口Interface1 依赖(使用)D类,但是只会用到1,4,5方法
 */
class C {
    public void depend1(Interface1 interface1) {
        interface1.operation1();
    }

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

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

 2.3 按照接口隔离方法改进

新的类图如下

package org.example.segtration;

public class Segregation1 {
    public static void main(String[] args) {
        A a = new A();
        a.depend1(new B()); //A类通过接口去依赖B类
        a.depend2(new B());
        a.depend3(new B());

        C c = new C();
        c.depend1(new D());//C类通过接口去依赖D类
        c.depend4(new D());
        c.depend5(new D());
    }
}

/**
 * Interface1 接口
 */
interface Interface1 {
    void operation1();
}

/**
 * Interface2 接口
 */
interface Interface2 {
    void operation2();
    void operation3();
}

/**
 * Interface3 接口
 */
interface Interface3 {
    void operation4();
    void operation5();
}
/**
 * 类B实现 Interface1、Interface2 接口,
 */
class B implements Interface1,Interface2{

    public void operation1() {
        System.out.println("B 实现了 operation1");
    }
    public void operation2() {
        System.out.println("B 实现了 operation2");
    }
    public void operation3() {
        System.out.println("B 实现了 operation3");
    }
}

/**
 * 类C实现 Interface1、Interface3 接口
 */
class D implements Interface1, Interface3{

    public void operation1() {
        System.out.println("D 实现了 operation1");
    }
    public void operation4() {
        System.out.println("D 实现了 operation4");
    }
    public void operation5() {
        System.out.println("D 实现了 operation5");
    }
}

class A {
    public void depend1(Interface1 interface1) {
        interface1.operation1();
    }

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

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

class C {
    public void depend1(Interface1 interface1) {
        interface1.operation1();
    }

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

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

3、依赖倒转原则

3.1 基本介绍

依赖倒转原则(Dependence Inversion Principle)是指:

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

3.2 应用实例

完成 Person 发送消息的功能。

案例一(传统方法)

package org.example.inversion;

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

class Email {
    public String getInfo() {
        return "电子邮件信息:hello,world";
    }
}

//完成 Person 接收消息的功能 -- 方式一
class Person {
    public void receive(Email email) {
        System.out.println(email.getInfo());
    }
}

分析: 

  • 简单,比较容易想到。
  • 问题:如果我们获取的对象是微信、短信等等,则要 新增类,同时 Person 也要增加相应的方法。

案例二(改进方法)

引入一个抽象的接口 IReceiver,表示接收者,这样 Person 类与 IReceiver接口发生依赖。因为 Email、Weixin 等都属于接收的范畴,他们各自实现 IReceiver接口,这样我们就符合依赖倒转原则。

package org.example.inversion;

public class DependencyInversion {
    public static void main(String[] args) {
        Person person = new Person();
        person.receive(new Email());
        person.receive(new Weixin());
    }
}

//定义接口
interface IReceiver {
    String getInfo();
}

class Email implements IReceiver {
    public String getInfo() {
        return "电子邮件信息:hello,world";
    }
}

class Weixin implements IReceiver {
    public String getInfo() {
        return "微信信息:hello,world";
    }
}

//完成 Person 接收消息的功能 -- 方式二
class Person {
    // 这里是对接口的依赖
    public void receive(IReceiver receiver) {
        System.out.println(receiver.getInfo());
    }
}

3.3 依赖关系传递的三种方式和应用案例 

依赖关系传递的三种方式:

  • 接口传递
  • 构造方法传递
  • setter方法传递

接口传递案例代码

package org.example.inversion;

public class Dependency {
    public static void main(String[] args) {
        OpenAndClose openAndClose = new OpenAndClose();
        openAndClose.open(new ChangHong());
    }
}

interface IOpenAndClose {
    /**
     * 抽象方法,接收接口
     * @param tv
     */
    void open(ITV tv);
}

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

/**
 * 实现接口:打开电视
 */
class OpenAndClose implements IOpenAndClose {
    public void open(ITV tv) {
        tv.play();
    }
}

/**
 * 定义长虹电视类
 */
class ChangHong implements ITV {

    public void play() {
        System.out.println("长虹电视打开了");
    }
}

构造方法传递案例代码

package org.example.inversion;

public class Dependency {
    public static void main(String[] args) {
        OpenAndClose openAndClose = new OpenAndClose(new ChangHong());
        openAndClose.open();
    }
}

/**
 * 定义有打开和关闭的接口
 */
interface IOpenAndClose {
    void open();
}

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

/**
 * 实现接口:打开电视
 */
class OpenAndClose implements IOpenAndClose {
    private ITV tv;

    public OpenAndClose(ITV tv) {
        this.tv = tv;
    }

    public void open() {
        tv.play();
    }
}

/**
 * 定义长虹电视类
 */
class ChangHong implements ITV {

    public void play() {
        System.out.println("长虹电视打开了");
    }
}

setter方法传递案例代码

package org.example.inversion;

public class Dependency {
    public static void main(String[] args) {
        OpenAndClose openAndClose = new OpenAndClose();
        openAndClose.setTv(new ChangHong());
        openAndClose.open();
    }
}

/**
 * 定义有打开和关闭的接口
 */
interface IOpenAndClose {
    void open();
    void setTv(ITV tv);
}

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

/**
 * 实现接口:打开电视
 */
class OpenAndClose implements IOpenAndClose {
    private ITV tv;

    public void setTv(ITV tv) {
        this.tv = tv;
    }

    public void open() {
        tv.play();
    }
}

/**
 * 定义长虹电视类
 */
class ChangHong implements ITV {

    public void play() {
        System.out.println("长虹电视打开了");
    }
}

3.4 依赖倒转原则的注意事项和细节

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

4、里式替换原则

4.1 OO中的继承性的思考和说明

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

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

问题:在编程中,如何正确的 使用继承?

里式替换原则

4.2 基本介绍

里式替换原则在1988年,由麻省理工学院的一位姓里的女士提出的。

如果对每个类型为 T1 的对象 o1,都有类型为 T2 的对象 o2,使得 T1 定义的所有程序 P 在所有对象o1替换成o2时,程序 P 的行为没有发生变化,那么类型T2是类型T1的子类型。换句话说,所有引用基类的地方必须能透明地使用其子类的对象。

在使用继承时,遵循里式替换原则,在子类中尽量不要重写父类的方法

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

4.3 一个程序引出的问题和思考

一个程序员不小心在子类重写父类的功能。

package org.example.liskov;

public class Liskov {
    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
        System.out.println("11+3+9=" + b.func2(11, 3));
    }
}
// A类
class A {
    // 返回两个数的差
    public int func1(int num1, int num2) {
        return num1 - num2;
    }
}

// B类继承了A
// 增加了一个新功能:完成两个数相加,然后和9求和
class B extends A {
    //这里,重写了A类的方法, 可能是无意识
    public int func1(int a, int b) {
        return a + b;
    }

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

4.4 解决办法

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

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

package org.example.liskov;

public class Liskov {
    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
        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();

    //自己的定义的两个数相加的方法
    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);
    }
}

5、开闭原则

5.1 基本介绍

开闭原则是编程中最基础、最重要的设计原则。

一个软件实体如类,模块和函数应该对扩展开放(对提供方),对修改关闭(对使用发放)。用抽象构建框架,用实现扩展细节。

当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,二不是通过修改已有的代码来实现变化

5.2 看下面代码

package org.example.opc;

public class Opc {
    public static void main(String[] args) {
        //使用看看存在的问题
        GraphicEditor graphicEditor = new GraphicEditor();
        graphicEditor.drawShape(new Rectangle());
        graphicEditor.drawShape(new Circle());
    }
}

//这是一个用于绘图的类 [使用方]
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(" 绘制圆形 ");
    }
}

//Shape类,基类
class Shape {
    int m_type;
}

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

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

5.3 方式1的优缺点

优点是比较好理解,简单易操作。

缺点是违反了设计模式的 ocp 原则,即对扩展开放,对修改关闭。即当我们给类增加新功能的时候,尽量不修改代码,或者尽可能少修改代码。

比如,我们这是要新增一个三角形,我们需要做如下修改,修改的地方较多。

package org.example.opc;

public class Opc {
    public static void main(String[] args) {
        //使用看看存在的问题
        GraphicEditor graphicEditor = new GraphicEditor();
        graphicEditor.drawShape(new Rectangle());
        graphicEditor.drawShape(new Circle());
        graphicEditor.drawShape(new Triangle());
    }
}

//这是一个用于绘图的类 [使用方]
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) { //需修改原始的 drawShape 方法
            drawTriangle(s);
        }
    }

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

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

    //绘制三角形
    public void drawTriangle(Shape r) {//需新增
        System.out.println(" 绘制三角形 ");
    }
}

//Shape类,基类
class Shape {
    int m_type;
}

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

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

//新增画三角形
class Triangle extends Shape {
    Triangle() {
        super.m_type = 3;
    }
}

5.4 改进的思路分析

Shape 类做成抽象类,并提供一个抽象的 draw 方法,让子类去实现即可,这样我们有新图案时,只需要让图形继承 Shape ,并实现 draw 方法即可,使用方的代码就不需要修改,即满足了开闭原则。

package org.example.opc;

public class Opc {
    public static void main(String[] args) {
        //使用看看存在的问题
        GraphicEditor graphicEditor = new GraphicEditor();
        graphicEditor.drawShape(new Rectangle());
        graphicEditor.drawShape(new Circle());
        graphicEditor.drawShape(new Triangle());
    }
}

//这是一个用于绘图的类 [使用方]
class GraphicEditor {
    //接收Shape对象,调用 draw 方法
    public void drawShape(Shape s) {
        s.draw();
    }
}

//Shape类,基类
abstract class Shape {
    int m_type;
    public abstract void draw();//抽象方法
}

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

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

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

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

//新增画三角形
class Triangle extends Shape {
    Triangle() {
        super.m_type = 3;
    }
    
    public void draw() {
        System.out.println(" 绘制三角形 ");
    }
}

6、迪米特法则

6.1 基本介绍

一个对象对其他对象保持最少的了解。

类与类关系越密切,耦合度越大。

迪米特法则又叫最少知道原则,即一个类对自己依赖的类知道的越少越好。也就是说,对于被依赖的类不管多么复杂,都尽量封装在类的内部。对外除了提供 public 方法,不对外泄露信息。

迪米特法则还有个更简单的定义:只与直接的朋友通信。

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

6.2 应用实例

有一个学校,下属有各个学院和总部,现要求打印出学校总部员工 ID 和 学院员工 ID。

以下代码是没有使用迪米特原则

package org.example.demeterr;

import java.util.ArrayList;
import java.util.List;

public class Demeter {
    public static void main(String[] args) {
        //创建了一个 SchoolManager 对象
        SchoolManager schoolManager = new SchoolManager();
        //输出学院的员工id 和  学校总部的员工信息
        schoolManager.printAllEmployee(new 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++) { //这里我们增加了10个员工到 list
            CollegeEmployee emp = new CollegeEmployee();
            emp.setId("学院员工id= " + i);
            list.add(emp);
        }
        return list;
    }
}

//学校管理类

//分析 SchoolManager 类的直接朋友类有哪些 Employee、CollegeManager
//CollegeEmployee 不是 直接朋友 而是一个陌生类,这样违背了 迪米特法则
class SchoolManager {
    //返回学校总部的员工
    public List<Employee> getAllEmployee() {
        List<Employee> list = new ArrayList<Employee>();

        for (int i = 0; i < 5; i++) { //这里我们增加了5个员工到 list
            Employee emp = new Employee();
            emp.setId("学校总部员工id= " + i);
            list.add(emp);
        }
        return list;
    }

    //该方法完成输出学校总部和学院员工信息(id)
    void printAllEmployee(CollegeManager sub) {

        //分析问题
        //1. 这里的 CollegeEmployee 不是  SchoolManager的直接朋友
        //2. CollegeEmployee 是以局部变量方式出现在 SchoolManager
        //3. 违反了 迪米特法则

        //获取到学院员工
        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());
        }
    }
}

6.3 应用实例改进

上面例子的问题在于:在 SchoolManager 中,CollegeEmployee  并不是 SchoolManager 的直接朋友。

按照迪米特法则,应该避免类中出现这样非直接朋友的耦合。

下面是代码实现

package org.example.demeterr;

import java.util.ArrayList;
import java.util.List;

public class Demeter {
    public static void main(String[] args) {
        //创建了一个 SchoolManager 对象
        SchoolManager schoolManager = new SchoolManager();
        //输出学院的员工id 和  学校总部的员工信息
        schoolManager.printAllEmployee(new 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++) { //这里我们增加了10个员工到 list
            CollegeEmployee emp = new CollegeEmployee();
            emp.setId("学院员工id= " + i);
            list.add(emp);
        }
        return list;
    }

    //输出学院员工的信息
    public void printEmployee() {
        //获取到学院员工
        List<CollegeEmployee> list1 = getAllEmployee();
        System.out.println("------------学院员工------------");
        for (CollegeEmployee e : list1) {
            System.out.println(e.getId());
        }
    }
}

//学校管理类
//分析 SchoolManager 类的直接朋友类有哪些 Employee、CollegeManager
class SchoolManager {
    //返回学校总部的员工
    public List<Employee> getAllEmployee() {
        List<Employee> list = new ArrayList<Employee>();

        for (int i = 0; i < 5; i++) { //这里我们增加了5个员工到 list
            Employee emp = new Employee();
            emp.setId("学校总部员工id= " + i);
            list.add(emp);
        }
        return list;
    }

    //该方法完成输出学校总部和学院员工信息(id)
    void printAllEmployee(CollegeManager sub) {
        //改进,我们这里调用 CollegeManager 的方法,避免了 CollegeEmployee 的出现
        sub.printEmployee();
        //获取到学校总部员工
        List<Employee> list2 = this.getAllEmployee();
        System.out.println("------------学校总部员工------------");
        for (Employee e : list2) {
            System.out.println(e.getId());
        }
    }
}

6.4 迪米特法则注意事项和细节

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

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

7、合成复用原则(Composite Reuse Principle)

原则尽量使用合成/聚合的方式,而不是使用继承。

如下图:如果B类使用A类中的方法,可以使用依赖、聚合、组合的方式去实现。

8、设计原则核心思想

找出应用中可能需要变化之处,把他们独立出来,不要和那些不需要变化的代码混在一起。

针对接口编程,而不是针对实现编程。

为了交互对象之间的松耦合设计而努力。

三、UML 画类图教程

1、UML 基本介绍

UML——Unified modeing language(统一建模语言),是一种用于软件系统分析和设计的语言工具,它用于帮助软件开发人员进行思考和记录思路的结果。

UML 本身是一套符号的规定,就像数学符号一样,这些符号用于描述软件模型中各个元素和他们之间的关系,比如 类、接口、实现、泛华、依赖、组合、聚合等,如下图:

使用 UML 来建模,常用的工具有 Rational Rose,也可以使用一些插件来建模。

我这边使用的是 Power Designer,新建 UML 类图方式如下:

  • 新建一个 study_uml 的工程
  • File->New Model
  • 选择 Categories -> 选择 Information -> UML Class Diagram
  • 输入名称,点击OK即可。

2、UML图

画UML图和写文章差不多,都是把自己的思想描述给别人看,关键在于思路和条理,UML图分类:

  • 用例图(use case)
  • 静态结构图:类图、对象图、包图、组件图、部署图
  • 动态行为图:交互图(时序图与协作图)、状态图、活动图

类图是描述类与类之间的关系的,是UML图中最核心的。

3、类图-依赖关系(Dependence)

只要是在类中用到了对方,那么他们之间就存在依赖关系。如果没有对方,连编译都通过不了。

例如下面代码:

public class PersonServiceBean {
    private PersonDao personDao;
    public void save(Person person){}
    public IDCard getIDCard(Integer personId){
        return null;
    }
    public void modify() {
        Depart depart = new Depart();
    }
}

class PersonDao {}
class IDCard {}
class Person {}
class Depart {}

对应的类图: PersonServiceBean  依赖于 personDao、IDCard、Person 、Depart 。

总结,依赖关系描述:

  • 类中用到了对方
  • 类的成员属性
  • 方法的返回类型
  • 方法接收的参数类型
  • 方法中使用(局部变量)

4、类图-泛化关系(Generalization)

泛化关系实际上就是继承关系,他是依赖关系的特例

public class PersonServiceBean extends DataSupport {
    public void save(Object entity){}
    public void delete(Object id){}
}

abstract class DataSupport {
    public void save(Object entity){}
    public void delete(Object id){}
}

 

泛化实际上就是继承,如果A继承了B,我们就说 A 和 B 存在泛化关系。 

5、类图-实现关系(Realization)

实现关系实际上就是 A类 实现 B接口,它就是 依赖关系的特例

public class PersonServiceBean implements PersonService {
    public void delete(Integer id) {}
}

interface PersonService {
    public void delete(Integer id);
}

6、类图-关联关系(Association)

关联关系实际上就是类与类之间的联系,他是依赖关系的特例

关联具有导航性:即双向关系或单向关系

关联具有多重性

  • “1”(表示有且仅有一个),
  • “0...”(表示0个或者多个),
  • “0,1”(表示0个或者一个),
  • “n...m”(表示n到m个都可以),
  • “m...*”(表示至少m个)

单向一对一关系

public class Person {
    private IDCard idCard;
}

class IDCard {}

 

双向一对一关系

public class Person {
    private IDCard idCard;
}

class IDCard {
    private Person person;
}

7、类图-聚合关系(Aggregation)

聚合关系(Aggregation)表示的是整体和部分的关系整体与部分可以分开聚合关系是关联关系的特例,所以也具有关联关系的导航性与多重性。

如一台电脑由键盘(keyboard)、显示器(monitor)、鼠标(mouse)等组成;组成电脑的各个配件是可以从电脑上分离出来的,使用带空心菱形的实现来表示。

public class Computer {
    private Keyboard keyboard;
    private Mouse mouse;
    private Monitor monitor;

    public void setKeyboard(Keyboard keyboard) {
        this.keyboard = keyboard;
    }

    public void setMouse(Mouse mouse) {
        this.mouse = mouse;
    }

    public void setMonitor(Monitor monitor) {
        this.monitor = monitor;
    }
}

class Keyboard {}
class Mouse {}
class Monitor {}

 记住,关联连接线detail属性中第二个输入0

8、类图-组合关系(Composition)

组合关系也是整体与部分的关系,但是整体和部分不可以分开

再看一个案例:在程序中我们定义实体: Person 与 IDCard、Head。Head和Person就是组合,IDCard和Person就是聚合。

但是如果在程序中 Person 实体中定义了对 IDCard 进行级联删除,即删除 Person 时连同 IDCard 一起删除,那么 IDCard 与 Person就是组合了。

public class Person {
    private IDCard card;
    private Head head = new Head();
}
class IDCard {}
class Head {}

 

9、总结 

依赖关系:只要是在类中用到了对方,那么他们之间就存在依赖关系。如果没有对方,连编译都过不了。

泛化关系:泛化关系实际上就是继承关系,它是依赖的特例。

实现关系:实现关系实际上就是A类实现B接口,它是依赖的特例。

关联关系:关联关系实际上就是类与类之间的联系,它是依赖的特例。

聚合关系:表示的是整体与部分的关系,整体与部分可以分开。聚合关系是关联关系的特例,所以他具有关联的导航性与多重性。

组合关系:也是整体与部分的关系,但是整体与部分不可以分开

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
本教程为授权出品教程1) 优秀的程序应该是这样的:阅读时,感觉很优雅;新增功能时,感觉很轻松;运行时,感觉很快速,这就需要设计模式支撑2) 设计模式包含了大量的编程思想,讲授和真正掌握并不容易,网上的设计模式课程不少,大多讲解的比较晦涩,没有真实的应用场景和框架源码支撑,学习后,只知其形,不知其神。就会造成这样结果: 知道各种设计模式,但是不知道怎么使用到真实项目。本课程针对上述问题,有针对性的进行了升级 (1) 授课方式采用 图解+框架源码分析的方式,让课程生动有趣好理解 (2) 系统全面的讲解了设计模式,包括 设计模式七大原则UML类图-类的六大关系、23种设计模式及其分类,比如 单例模式的8种实现方式、工厂模式的3种实现方式、适配器模式的3种实现、代理模式的3种方式、深拷贝等3) 如果你想写出规范、漂亮的程序,就花时间来学习设计模式吧课程内容和目标本课程是使用Java来讲解设计模式,考虑到设计模式比较抽象,授课采用 图解+框架源码分析的方式1) 内容包括:设计模式七大原则(单一职责、接口隔离、依赖倒转、里氏替换、开闭原则、迪米特法则、合成复用)、UML类图(类的依赖、泛化和实现、类的关联、聚合和组合) 23种设计模式包括:创建型模式:单例模式(8种实现)、抽象工厂模式、原型模式、建造者模式、工厂模式。结构型模式:适配器模式(3种实现)、桥接模式、装饰模式、组合模式、外观模式、享元模式、代理模式(3种实现)。行为型模式:模版方法模式、命令模式、访问者模式、迭代器模式、观察者模式、中介者模式、备忘录模式、解释器模式(Interpreter模式)、状态模式、策略模式、职责链模式(责任链模式)。2) 学习目标:通过学习,学员能掌握主流设计模式,规范编程风格,提高优化程序结构和效率的能力。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值