设计模式7大原则

1.单一职责原则

基本介绍

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

不好的案例

/**
 * @author luoyong
 * @Description: Vehicle
 * 交通工具
 * @create 2019-08-28 22:45
 * @last modify by [LuoYong 2019-08-28 22:45]
 **/
@Data
public class Vehicle {
    public void run(String vehicle) {
        System.out.println(vehicle + " 在公路上运行....");
    }
}
/**
 * @author luoyong
 * @Description: SingleResponsibilityBad
 * 单一原则错误示例
 * @create 2019-08-28 22:44
 * @last modify by [LuoYong 2019-08-28 22:44]
 **/
public class SingleResponsibilityBad {

    /**
     * @param
     * @return void
     * @Description: 不好的示例 违反了单一职责原则
     * @author luoyong
     * @create 22:50 2019/8/28
     * @last modify by [LuoYong 22:50 2019/8/28 ]
     */
    @Test
    public void testBadSingleResponsibility() {
        Vehicle vehicle = new Vehicle();
        vehicle.run("摩托车");
        vehicle.run("汽车");
        vehicle.run("飞机");
    }

}

改进(单一职责多个类)

/**
 * @author luoyong
 * @Description: SingleResponsibilityWithMultiClass
 * @create 2019-08-28 22:53
 * @last modify by [LuoYong 2019-08-28 22:53]
 **/
public class SingleResponsibilityWithMultiClass {

    /**
     * @param
     * @return void
     * @Description: 多个类
     * 遵守单一职责原则
     * 但是这样改动很大 1:类分解 2:修改客户端
     * @author luoyong
     * @create 22:53 2019/8/28
     * @last modify by [LuoYong 22:53 2019/8/28 ]
     */
    @Test
    public void testSingleResponsibilityWithMoreClass() {
        RoadVehicle roadVehicle = new RoadVehicle();
        roadVehicle.run("摩托车");
        roadVehicle.run("汽车");
        AirVehicle airVehicle = new AirVehicle();
        airVehicle.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 + "水中运行");
        }
    }
}

改进(单一职责多个方法)

/**
 * @author luoyong
 * @Description: SingleResponsibilityWithMoreMethod
 * @create 2019-08-28 22:56
 * @last modify by [LuoYong 2019-08-28 22:56]
 **/
public class SingleResponsibilityWithMultiMethod {

    /**
     * @param
     * @return void
     * @Description: testSingleResponsibilityWithMultiMethod
     * 这种修改方法没有对原来的类做大的修改,只是增加方法
     * 这里虽然没有在类这个级别上遵守单一职责原则,但是在方法级别上,仍然是遵守单一职责
     * @author luoyong
     * @create 22:57 2019/8/28
     * @last modify by [LuoYong 22:57 2019/8/28 ]
     */
    @Test
    public void testSingleResponsibilityWithMultiMethod() {
        VehicleMultiMethod vehicleMultiMethod = new VehicleMultiMethod();
        vehicleMultiMethod.run("汽车");
        vehicleMultiMethod.runWater("轮船");
        vehicleMultiMethod.runAir("飞机");
    }

    class VehicleMultiMethod {
        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 + " 在水中行....");
        }
    }
}

注意事项和细节

1 ) 降 低 类 的 复 杂 度 , 一 个 类 只 负 责 一 项 职 责 \color{red}{1) 降低类的复杂度,一个类只负责一项职责} 1)
2 ) 提 高 类 的 可 读 性 , 可 维 护 性 \color{red}{2) 提高类的可读性,可维护性} 2)
3 ) 降 低 变 更 引 起 的 风 险 \color{red}{3) 降低变更引起的风险} 3)
4 ) 通 常 情 况 下 , 我 们 应 当 遵 守 单 一 职 责 原 则 , 只 有 逻 辑 足 够 简 单 , 才 可 以 在 代 码 级 违 反 单 一 职 责 原 则 ; 只 有 类 中 方 法 数 量 足 够 少 , 可 以 在 方 法 级 别 保 持 单 一 职 责 原 则 \color{red}{4) 通常情况下,我们应当遵守单一职责原则,只有逻辑足够简单,才可以在代码级违 反单一职责原则;只有类中方法数量足够少,可以在方法级别保持单一职责原则} 4);

2.接口隔离原则

基本介绍

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

案例分析

在这里插入图片描述

package com.ly.senior.designpatterns.principle.segregation.bad;

/**
 * @author luoyong
 * @Description: SegregationBad
 * @create 2019-08-29 8:03
 * @last modify by [LuoYong 2019-08-29 8:03]
 **/
public class SegregationBad {
    public static void main(String[] args) {

        // A类通过接口去依赖B类
        A a = new A();
        a.dependOne(new B());
        a.dependTwo(new B());
        a.dependThree(new B());

        // C类通过接口去依赖(使用)D类
        C c = new C();
        c.dependOne(new D());
        c.dependFour(new D());
        c.dependFive(new D());

    }
}

interface InterfaceBad {
    void operationOne();

    void operationTwo();

    void operationThree();

    void operationFour();

    void operationFive();
}

class B implements InterfaceBad {
    public void operationOne() {
        System.out.println("B 实现了 operation1");
    }

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

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

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

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

class D implements InterfaceBad {
    public void operationOne() {
        System.out.println("D 实现了 operation1");
    }

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

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

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

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

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

    public void dependTwo(InterfaceBad i) {
        i.operationTwo();
    }

    public void dependThree(InterfaceBad i) {
        i.operationThree();
    }
}

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

    public void dependFour(InterfaceBad i) {
        i.operationFour();
    }

    public void dependFive(InterfaceBad i) {
        i.operationFive();
    }
}

分析

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

改进

package com.ly.senior.designpatterns.principle.segregation.improve;

import org.junit.Test;

/**
 * @author luoyong
 * @Description: SegregationImprove
 * @create 2019-08-29 22:53
 * @last modify by [LuoYong 2019-08-29 22:53]
 **/
public class SegregationImprove {

    /**
     * @param
     * @return void
     * @Description: 测试接口隔离原则
     * @author luoyong
     * @create 23:01 2019/8/29
     * @last modify by [LuoYong 23:01 2019/8/29 ]
     */
    @Test
    public void test() {
        // A类通过接口去依赖B类
        A a = new A();
        a.dependOne(new B());
        a.dependTwo(new B());
        a.dependThree(new B());

        //C类通过接口去依赖(使用)D类
        C c = new C();
        c.dependOne(new D());
        c.dependFour(new D());
        c.dependFive(new D());
    }
}


/**
 * 接口1
 */
interface InterfaceOne {
    void operationOne();
}

/**
 * 接口2
 */
interface InterfaceTwo {
    void operationTwo();

    void operationThree();
}

/**
 * 接口3
 */
interface InterfaceThree {
    void operationFour();

    void operationFive();
}


class B implements InterfaceOne, InterfaceTwo {
    public void operationOne() {
        System.out.println("B 实现了 operationOne");
    }

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

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

}

class D implements InterfaceOne, InterfaceThree {
    @Override
    public void operationOne() {
        System.out.println("D 实现了operationOne");
    }

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

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

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

    public void dependTwo(InterfaceTwo i) {
        i.operationTwo();
    }

    public void dependThree(InterfaceTwo i) {
        i.operationThree();
    }
}

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

    public void dependFour(InterfaceThree i) {
        i.operationFour();
    }

    public void dependFive(InterfaceThree i) {
        i.operationFive();
    }
}

3.依赖倒转(倒置原则)

依赖关系传递的三种方式

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

案例

package com.ly.senior.designpatterns.principle.inversion.bad;

import org.junit.Test;

/**
 * @author luoyong
 * @Description: DependecyInversionBad
 * @create 2019-08-29 23:32
 * @last modify by [LuoYong 2019-08-29 23:32]
 **/
public class DependecyInversionBad {

    /**
     * @param
     * @return void
     * @Description: test
     * @author luoyong
     * @create 23:36 2019/8/29
     * @last modify by [LuoYong 23:36 2019/8/29 ]
     */
    @Test
    public void test() {
        Person p = new Person();
        p.receive(new Email());
    }
}

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

/**
 * 完成Person接收消息功能
 * 1. 如果我们获取的对象是 微信,短信等等,则新增类,同时Perons也要增加相应的接收方法
 * 2: 解决思路:引入一个抽象的接口IReceiver, 表示接收者, 这样Person类与接口IReceiver发生依赖'
 * 3: 因为Email, WeiXin 等等属于接收的范围,他们各自实现IReceiver 接口就ok, 这样我们就符号依赖倒转原则
 */
class Person {
    public void receive(Email email) {
        System.out.println(email.getInfo());
    }
}

改进

package com.ly.senior.designpatterns.principle.inversion.improve;

import org.junit.Test;

/**
 * @author luoyong
 * @Description: DependecyInversionImprove 面向接口编程
 * @create 2019-08-29 23:35
 * @last modify by [LuoYong 2019-08-29 23:35]
 **/
public class DependecyInversionImprove {

    /**
     * @param
     * @return void
     * @Description: 依赖倒转原则--面向接口编程
     * @author luoyong
     * @create 23:42 2019/8/29
     * @last modify by [LuoYong 23:42 2019/8/29 ]
     */
    @Test
    public void test() {
        Person person = new Person();
        //电子邮件
        person.receive(new EmailReceiverImpl());
        //微信
        person.receive(new WeChatReceiverImpl());
    }
}


/**
 * 接收消息接口
 */
interface IReceiver {
    String getInfo();
}

/**
 * 电子邮件消息
 */
class EmailReceiverImpl implements IReceiver {
    @Override
    public String getInfo() {
        return "电子邮件信息: hello,world";
    }
}

/**
 * 微信消息
 */
class WeChatReceiverImpl implements IReceiver {
    @Override
    public String getInfo() {
        return "WeChat: hello WeChat";
    }
}


/**
 * 面向接口编程
 */
class Person {
    public void receive(IReceiver iReceiver) {
        System.out.println(iReceiver.getInfo());
    }
}

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

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

4.里氏替换原则

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

  1. 继承包含这样一层含义:父类中凡是已经实现好的方法,实际上是在设定规范和契
    约,虽然它不强制要求所有的子类必须遵循这些契约,但是如果子类对这些已经实现的方法任意修改,就会对整个继承体系造成破坏。
  2. 继承在给程序设计带来便利的同时,也带来了弊端。比如使用继承会给程序带来侵 入性,程序的可移植性降低,增加对象间的耦合性,如果一个类被其他的类所继承, 则当这个类需要修改时,必须考虑到所有的子类,并且父类修改后,所有涉及到子 类的功能都有可能产生故障。
  3. 问题提出:在编程中,如何正确的使用继承? => 里氏替换原则

基本介绍

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

案例

package com.ly.senior.designpatterns.principle.liskov.bad;

import org.junit.Test;

/**
 * @author luoyong
 * @Description: LiskovBad 里式替换原则
 * @create 2019-09-01 11:05
 * @last modify by [LuoYong 2019-09-01 11:05]
 **/
public class LiskovBad {
    @Test
    public void test() {
        A a = new A();
        System.out.println("11-3=" + a.funcOne(11, 3));
        System.out.println("1-8=" + a.funcOne(1, 8));

        System.out.println("-----------------------");
        B b = new B();
        //这里本意是求出11-3 但是B重写了funcOne方法
        System.out.println("11-3=" + b.funcOne(11, 3));
        // 1-8
        System.out.println("1-8=" + b.funcOne(1, 8));
        System.out.println("11+3+9=" + b.funcTwo(11, 3));


    }
}

class A {
    public int funcOne(int numOne, int numTwo) {
        return numOne - numTwo;
    }
}


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

    public int funcTwo(int a, int b) {
        return funcOne(a, b) + 9;
    }
}

改进

package com.ly.senior.designpatterns.principle.liskov.improve;

import org.junit.Test;

/**
 * @author luoyong
 * @Description: 里式替换原则
 * @create 2019-09-01 15:41
 * @last modify by [LuoYong 2019-09-01 15:41]
 **/
public class LiskovImprove {
    @Test
    public void test() {
        A a = new A();
        System.out.println("11-3=" + a.funcOne(11, 3));
        System.out.println("1-8=" + a.funcOne(1, 8));

        System.out.println("-----------------------");
        B b = new B();
        //因为B类不再继承A类,因此调用者,不会再funcOne是求减法
        //调用完成的功能就会很明确
        //这里本意是求出11+3
        System.out.println("11+3=" + b.funcOne(11, 3));
        // 1+8
        System.out.println("1+8=" + b.funcOne(1, 8));

        System.out.println("11+3+9=" + b.funcTwo(11, 3));

        //使用组合仍然可以使用到A类相关方法
        // 这里本意是求出11-3
        b.setA(a);
        System.out.println("11-3=" + b.funcThree(11, 3));

    }
}


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

/**
 * A类
 */
class A extends Base {
    /**
     * @param a
     * @param b
     * @return int
     * @Description: 返回两个数的差
     * @author luoyong
     * @create 15:43 2019/9/1
     * @last modify by [LuoYong 15:43 2019/9/1 ]
     */
    public int funcOne(int a, int b) {
        return a - b;
    }
}

class B extends Base {
    //如果B需要使用A类的方法,使用组合关系
    private A a;

    public void setA(A a) {
        this.a = a;
    }

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

    public int funcTwo(int a, int b) {
        return funcOne(a, b) + 9;
    }

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

5.开闭原则

基本介绍

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

案例

package com.ly.senior.designpatterns.principle.ocp.bad;

import org.junit.Test;

/**
 * @author luoyong
 * @Description: OcpBad 开闭原则
 * @create 2019-09-01 17:14
 * @last modify by [LuoYong 2019-09-01 17:14]
 **/
public class OcpBad {

    @Test
    public void test() {
        GraphicEditor graphicEditor = new GraphicEditor();
        graphicEditor.drawShape(new Rectangle());
        graphicEditor.drawShape(new Circle());
        graphicEditor.drawShape(new Triangle());
    }
}


/**
 * 这是一个用于绘图的类 [使用方]
 */
class GraphicEditor {
    /**
     * 接收Shape对象,然后根据type,来绘制不同的图形
     *
     * @param s
     */
    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);
        }

    }

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


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

    /**
     * 绘制三角形
     * 新增的代码
     *
     * @param r
     */
    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;
    }
}

改进

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

package com.ly.senior.designpatterns.principle.ocp.improve;

import org.junit.Test;

/**
 * @author luoyong
 * @Description: OcpBadImprove 开闭原则案例
 * @create 2019-09-01 17:19
 * @last modify by [LuoYong 2019-09-01 17:19]
 **/
public class OcpBadImprove {
    @Test
    public void test() {
        GraphicEditor graphicEditor = new GraphicEditor();
        graphicEditor.drawShape(new Rectangle());
        graphicEditor.drawShape(new Circle());
        graphicEditor.drawShape(new Triangle());
        graphicEditor.drawShape(new Other());
    }
}


/**
 * 这是一个用于绘图的类 [使用方]
 */
class GraphicEditor {
    public void drawShape(Shape shape) {
        shape.draw();
    }
}

abstract class Shape {
    int m_type;

    abstract void draw();
}

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

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

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

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

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

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

class Other extends Shape {
    Other() {
        super.m_type = 4;
    }

    @Override
    void draw() {
        System.out.println(" 绘制其他图形 ");
    }
}

6.迪米特法则

基本介绍

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

案例

package com.ly.senior.designpatterns.principle.demeter;

import com.google.common.collect.Lists;
import org.junit.Test;

import java.util.List;

/**
 * @author luoyong
 * @Description: DemeterBad 迪米特法则 一个类对自己依赖的类知道的越少越好
 * @create 2019-09-02 22:24
 * @last modify by [LuoYong 2019-09-02 22:24]
 **/
public class DemeterBad {
    @Test
    public void  test(){
        SchoolManager schoolManager=new SchoolManager();
        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 {
    /**
     * @param
     * @return
     * @Description: 返回学院的所有员工
     * @author luoyong
     * @create 22:26 2019/9/2
     * @last modify by [LuoYong 22:26 2019/9/2 ]
     */
    public List<CollegeEmployee> getAllEmployee() {
        List<CollegeEmployee> list = Lists.newArrayList();
        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 {
    /**
     * @param
     * @return
     * @Description: 返回学校总部的员工
     * @author luoyong
     * @create 22:27 2019/9/2
     * @last modify by [LuoYong 22:27 2019/9/2 ]
     */
    public List<Employee> getAllEmployee() {
        List<Employee> list = Lists.newArrayList();
        //这里我们增加了5个员工到 list
        for (int i = 0; i < 5; i++) {
            //这里我们增加了5个员工到 list
            Employee emp = new Employee();
            emp.setId("学校总部员工id= " + i);
            list.add(emp);
        }
        return list;
    }
    /**
     * @param sub
     * @return void
     * @Description: 该方法完成输出学校总部和学院员工信息(id)
     * @author luoyong
     * @create 22:28 2019/9/2
     * @last modify by [LuoYong 22:28 2019/9/2 ]
     */
    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());
        }
    }
}

改进

package com.ly.senior.designpatterns.principle.demeter.improve;

import com.google.common.collect.Lists;
import org.junit.Test;

import java.util.List;

/**
 * @author luoyong
 * @Description: DemeterBad 迪米特法则 一个类对自己依赖的类知道的越少越好 改进
 * @create 2019-09-02 22:24
 * @last modify by [LuoYong 2019-09-02 22:24]
 **/
public class DemeterImprove {
    @Test
    public void test() {
        SchoolManager schoolManager = new SchoolManager();
        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 {
    /**
     * @param
     * @return
     * @Description: 返回学院的所有员工
     * @author luoyong
     * @create 22:26 2019/9/2
     * @last modify by [LuoYong 22:26 2019/9/2 ]
     */
    public List<CollegeEmployee> getAllEmployee() {
        List<CollegeEmployee> list = Lists.newArrayList();
        for (int i = 0; i < 10; i++) {
            //这里我们增加了10个员工到 list
            CollegeEmployee emp = new CollegeEmployee();
            emp.setId("学院员工id= " + i);
            list.add(emp);
        }
        return list;
    }

    /**
     * @param
     * @return void
     * @Description: 打印学院员工的所有信息(id)
     * @author luoyong
     * @create 22:31 2019/9/2
     * @last modify by [LuoYong 22:31 2019/9/2 ]
     */
    void printCollegeAllEmployee() {
        List<CollegeEmployee> list1 = this.getAllEmployee();
        System.out.println("------------学院员工------------");
        for (CollegeEmployee e : list1) {
            System.out.println(e.getId());
        }
    }
}

/**
 * 学校管理类
 * 直接朋友:成员变量 方法参数 方法返回值
 * SchoolManager 类的直接朋友类有哪些 Employee、CollegeManager
 * CollegeEmployee 不是 直接朋友 而是一个陌生类,这样违背了 迪米特法则
 */
class SchoolManager {
    /**
     * @param
     * @return
     * @Description: 返回学校总部的员工
     * @author luoyong
     * @create 22:27 2019/9/2
     * @last modify by [LuoYong 22:27 2019/9/2 ]
     */
    public List<Employee> getAllEmployee() {
        List<Employee> list = Lists.newArrayList();
        //这里我们增加了5个员工到 list
        for (int i = 0; i < 5; i++) {
            //这里我们增加了5个员工到 list
            Employee emp = new Employee();
            emp.setId("学校总部员工id= " + i);
            list.add(emp);
        }
        return list;
    }

    /**
     * @param sub
     * @return void
     * @Description: 该方法完成输出学校总部和学院员工信息(id)
     * @author luoyong
     * @create 22:28 2019/9/2
     * @last modify by [LuoYong 22:28 2019/9/2 ]
     */
    void printAllEmployee(CollegeManager sub) {
        //打印所有学院员工信息
        sub.printCollegeAllEmployee();
        //获取到学校总部员工
        List<Employee> list2 = this.getAllEmployee();
        System.out.println("------------学校总部员工------------");
        for (Employee e : list2) {
            System.out.println(e.getId());
        }
    }
}

注意事项和细节

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

7.合成复用原则

基本介绍

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值