JustNote
  • Introduction
  • DesignPattern
    • 七大原则
      • 开闭原则(OCP)
      • 依赖倒置原则(DIP)
      • 单一职责原则(SRP)
      • 接口隔离原则(ISP)
      • 迪米特法则(LoD)
      • 里氏代换原则(LSP)
      • 合成复用原则(CRP)
    • 创建型模式
      • 简单工厂模式
      • 工厂方法模式
      • 抽象工厂模式
      • 建造者模式
      • 单例模式
      • 原型模式
    • 结构型模式
      • 外观模式
      • 装饰模式
      • 适配器模式
      • 享元模式
      • 组合模式
      • 桥接模式
      • 代理模式
    • 行为型模式
      • 模板方法模式
      • 迭代器模式
      • 策略模式
      • 解释器模式
      • 观察者模式
      • 备忘录模式
      • 命令模式
      • 中介者模式
      • 责任链模式
      • 访问者模式
      • 状态模式
  • Java
    • Java Core
      • JVM 如何加载类
      • JVM 垃圾回收
      • JVM G1GC
      • JVM G1GC Q&A
      • JVM 与 Hbase
      • JVM ZGC Overview
      • JVM ZGC 内存管理
      • JVM ZGC 线程
      • JVM ZGC 垃圾回收
      • JVM ZGC 日志分析
      • JVM ZGC 参数调优
    • checkstyle
  • Golang
    • 源码阅读
      • Goroutines
      • Channel
    • gRPC
      • 1、快速开始
      • 2、什么是gRPC
      • 3、gRPC概念梳理
      • 4、基于Golang的gRPC入门
      • 5、gRPC组件ProtocolBuffers介绍
      • 6、gRPC组件Http 2.0
      • 7、错误处理和Debug
      • 8、gRPC身份验证
      • 9、服务注册与发现
      • 10、gRPC与gRPC Gateway
      • 11、gRPC与分布式链路追踪
  • Scala
    • 数据结构与算法
      • 数组
      • 队列
    • 函数式编程
      • 高阶函数
      • 偏函数
    • Immutable Collection
      • List
    • Mutable Collection
      • Array
    • 常见函数操作
      • A
        • aggregate
        • andThen
        • appended
        • appendedAll
      • C
        • chain
        • collect
        • collectFirst
        • combinations
        • compose
        • concat
        • cond
        • condOpt
        • const
        • contains
        • containsSlice
        • copyToArray
        • corresponds
        • count
        • curried
      • D
        • diff
        • distinct
        • distinctBy
        • drop
        • dropRight
        • dropWhile
      • E
        • empty(PartialFunction)
        • empty(collections)
        • endsWith
        • exists
      • F
        • fill
        • filter
        • filterKeys
        • filterNot
        • find
        • findLast
        • flatMap
        • flatten
        • fold
        • foldLeft
        • foldRight
        • forall
        • foreach
        • fromFunction
      • G
        • getOrElse (Map)
        • getOrElse (Option)
        • groupBy
        • groupMap
        • groupMapReduce
        • grouped
      • H
        • head
        • headOption
      • I
        • indexOf
        • indexOfSlice
        • indexWhere
        • indices
        • init
        • inits
        • intersect
        • isDefinedAt (Map)
        • isDefinedAt (Seq)
        • isEmpty
        • isTraversableAgain
      • K
        • keys
      • L
        • last
        • lastIndexOf
        • lastIndexOfSlice
        • lastIndexWhere
        • lastOption
        • length
        • lift
      • M
        • map
        • mapConserve
        • mapValues
        • max
        • maxBy
        • maxByOption
        • maxOption
        • min
        • minBy
        • minByOption
        • minOption
        • mkString
      • N
        • nonEmpty
      • O
        • orElse
      • P
        • padTo
        • par
        • partition
        • partitionMap
        • patch
        • permutations
        • prefixLength
        • prepended
        • prependedAll
        • product
      • R
        • range
        • reduce
        • reduceLeft
        • reduceLeftOption
        • reduceOption
        • reduceRight
        • reduceRightOption
        • reverse
        • reverseIterator
        • reverseMap
        • runWith
      • S
        • sameElements
        • scan
        • scanLeft
        • scanRight
        • search
        • segmentLength
        • size
        • slice
        • sliding
        • sortBy
        • sortWith
        • sorted
        • span
        • splitAt
        • startsWith
        • sum
      • T
        • tabulate
        • tail
        • tails
        • take
        • takeRight
        • takeWhile
        • transpose
        • tupled
      • U
        • unfold
        • union
        • unlift
        • untupled
        • unzip
        • unzip3
        • updated
      • V
        • values
        • view
      • W
        • withFilter
        • withDefault
        • withDefaultValue
      • Z
        • zip
        • zipAll
        • zipWithIndex
      • map
      • flatmap
      • filter
      • reduceLeft
      • foldLeft
    • Futures
      • Method with future as return type
      • Non blocking future result
      • Chain futures using flatMap
      • Chain futures using for comprehension
      • Future Option with for comprehension
      • Future Option with map
      • Composing Futures
      • Future Sequence
      • Future Traverse
      • Future foldLeft
      • Future reduceLeft
      • Future firstCompletedOf
      • Future zip
      • Future zipWith
      • Future andThen
      • Future configure threadpool
      • Future recover
      • Future recoverWith
      • Future fallbackTo
      • Future promise
    • Akka
  • Algorithm
  • Docker
  • Kubernetes
    • 二进制安装kubernetes
      • 00.从零开始
  • Architecture
    • Infrastructure
      • Opentracing
      • Jaeger && ZipKin
      • SkyWalking
      • Consul
      • Envoy
      • Service Mesh
      • Service Mesh: Istio 详解
      • Service Mesh: 基于 Istio 的落地实践(一)
    • CAS
      • CAS Server
      • CAS Service Management
      • CAS 集成LDAP
      • CAS 集成gitlab
      • CAS SSO & SLO
      • CAS Gitbook
    • xCAT
  • Netty
  • DDD
  • Reactive Programming
    • Reactor
      • Publisher
      • Subscriber
      • Subscription
      • Processor
    • WebFlux
  • Gitlab
    • Git Hook
  • CICD
    • Jenkins
      • Kubectl
Powered by GitBook
On this page
  • Golang Demo
  • Java Demo
  • 接口单一职责原则的体现
  • 类单一职责原则的体现。
  • UML (接口为例)
  • 补充另一个版本的Java/Scala Demo 以及源码解析
  • Java Demo_
  • Scala Demo
  • UML_
  • 源码解析

Was this helpful?

  1. DesignPattern
  2. 七大原则

单一职责原则(SRP)

   单一职责原则(Single Responsibility Principle, SRP):一个类只负责一个功能领域中的相应职责,或者可以定义为:就一个类而言,应该只有一个引起它变化的原因,不要存在多于一个导致类变更的原因。一个类/接口/方法只负责一项职责。    单一职责原则是高内聚低耦合的指导方针,可以降低类的复杂度,提高类的可读性,提高系统的可维护性、降低变更引起的风险。其实,通俗来理解,一个类不能太累。我们在传统的软件工程,或者老旧的系统中经常能够看到,一个代码上万行的类。这种情况可能是由于历史原因导致的,但是不可否认,维护起来难度简直太大。因此,我们在软件设计过程中,要尝试将职责进行分离,不通职责封装在不同的类中,这样就能够降低我们设计软件的复杂度了。    单一职责原则不仅仅适用于面向对象编程语言设计,只要是模块化的编程,都适用。

Golang Demo

接下来,我们以接口为例,来看看单一职责原则在golang编程中的体现。详细的例子可以参考下面的Java Demo.

package singleresponsibility

type CourseContent interface {
  getCourseName() string

  getCourseVideo() []byte
}
package singleresponsibility

type CourseManager interface {
  studyCourse()

  refundCourse()
}
package singleresponsibility

import "fmt"

type Course struct {
}

func (Course) studyCourse() {
  fmt.Println("study")
}

func (Course) refundCourse() {
  fmt.Println("refund")
}

func (Course) getCourseName() string {
  return "course name"
}

func (Course) getCourseVideo() []byte {
  return nil
}

Java Demo

接口单一职责原则的体现

假设我们有下面这样一个接口。这个接口里面 既有获取信息,又有对课程的的操作等行为。

package tech.selinux.design.principle.singleresponsibility;

public interface ICourse {
  String getCourseName();

  byte[] getCourseVideo();

  void studyCourse();

  void refundCourse();
}

我们就可以对接口中的行为进行分类,使得每个接口具有单一职责。实现类可以实现多个接口就可以了。

package tech.selinux.design.principle.singleresponsibility;

public interface ICourseContent {

  String getCourseName();

  byte[] getCourseVideo();
}
package tech.selinux.design.principle.singleresponsibility;

public interface ICourseManager {

  void studyCourse();

  void refundCourse();
}
package tech.selinux.design.principle.singleresponsibility;

public class CourseImpl implements ICourseManager, ICourseContent {
  @Override
  public void studyCourse() {}

  @Override
  public void refundCourse() {}

  @Override
  public String getCourseName() {
    return null;
  }

  @Override
  public byte[] getCourseVideo() {
    return new byte[0];
  }
}

类单一职责原则的体现。

假设我们有下面一个类。

package tech.selinux.design.principle.singleresponsibility;

public class Bird {
  public void mainMoveMode(String birdName) {
    if ("鸵鸟".equals(birdName)) {
      System.out.println(birdName + "用脚走");
    } else {
      System.out.println(birdName + "用翅膀飞");
    }
  }
}

如果后期,我们需要增加许多新的鸟类,那这个类将变的无比庞杂,所以,我们可以定义几个只有单一职责的类。

package tech.selinux.design.principle.singleresponsibility;

public class FlyBird {
  public void mainMoveMode(String birdName) {
    System.out.println(birdName + "用翅膀飞");
  }
}
package tech.selinux.design.principle.singleresponsibility;

public class WalkBird {
  public void mainMoveMode(String birdName) {
    System.out.println(birdName + "用脚走");
  }
}
package tech.selinux.design.principle.singleresponsibility;

public class Test {
  public static void main(String[] args) {
    FlyBird flyBird = new FlyBird();
    flyBird.mainMoveMode("大雁");

    WalkBird walkBird = new WalkBird();
    walkBird.mainMoveMode("鸵鸟");
  }
}

UML (接口为例)

补充另一个版本的Java/Scala Demo 以及源码解析

Java Demo_

Scala Demo

UML_

源码解析

Previous依赖倒置原则(DIP)Next接口隔离原则(ISP)

Last updated 5 years ago

Was this helpful?

接口单一职责UML