空对象设计模式是一种行为型设计模式,主要用于应对空对象的检查。使用这种设计模式可以避免对空对象进行检查。也就是说,在这种模式下,使用空对象不会造成异常。

空对象模式的组件包括:

  • Entity:接口,定义了子struct需要实现的方法
  • ConcreteEntity:实现了Entity 的具体struct
  • NullEntity:这个就表示了空对象,虽然也实现了Entity接口,但它的值都是空的
  • Client:这个类会获取Entity接口实现类的实例并使用它。这里并不关注实现类是ConcreteEntity 还是 NullEntity,对二者会进行相同的处理。

用个例子来说一下:假设有一所大学,大学有多个系,每个系都有一定数量的教授。

系(department)可以用一个接口来表示:

type department interface {
getNumberOfProfessors() int getName() string
}

大学(college)也是一个接口:

type college struct {
departments []department
}

现在假设有一个机构想统计下大学每个系的教授数量。

在这个例子里,假设大学里没有某个系,我们就会用到空对象模式。这里定义了一个nullDepartment来表示不存在的系。

nullDepartment.go:

type nullDepartment struct {
numberOfProfessors int
} func (c *nullDepartment) getNumberOfProfessors() int {
return 0
} func (c *nullDepartment) getName() string {
return "nullDepartment"
}

统计的代码在agency.go里:

func main() {
college1 := createCollege1()
college2 := createCollege2()
totalProfessors := 0
departmentArray := []string{"computerScience", "mechanical", "civil", "electronics"} for _, departmentName := range departmentArray {
d := college1.getDepartment(departmentName)
totalProfessors += d.getNumberOfProfessors()
} fmt.Printf("Total number of professors in college1 is %d\n", totalProfessors) //Reset the professor count
totalProfessors = 0
for _, departmentName := range departmentArray {
d := college2.getDepartment(departmentName)
totalProfessors += d.getNumberOfProfessors()
}
fmt.Printf("Total number of professors in college2 is %d\n", totalProfessors)
} func createCollege1() *college {
college := &college{}
college.addDepartment("computerScience", 4)
college.addDepartment("mechanical", 5)
return college
} func createCollege2() *college {
college := &college{}
college.addDepartment("computerScience", 2)
return college
}

注意这段代码:

  • agency.go 并不关心某个系在大学里是否存在。当这个系不存在时,大学只需要返回一个nullDepartment对象即可
  • agency.go 对nullDepartment对象和其他department实现类的对象做了相同处理,这之中不需要对空值进行检查,直接调用getNumberOfProfessors()就可以了

以上就是使用空对象模式的好处了。

下面是其他的代码。

college.go:

type college struct {
departments []department
} func (c *college) addDepartment(departmentName string, numOfProfessors int) {
if departmentName == "computerScience" {
computerScienceDepartment := &computerScience{numberOfProfessors: numOfProfessors}
c.departments = append(c.departments, computerScienceDepartment)
}
if departmentName == "mechanical" {
mechanicalDepartment := &mechanical{numberOfProfessors: numOfProfessors}
c.departments = append(c.departments, mechanicalDepartment)
}
return
} func (c *college) getDepartment(departmentName string) department {
for _, department := range c.departments {
if department.getName() == departmentName {
return department
}
}
//Return a null department if the department doesn't exits
return &nullDepartment{}
}

计算机系,computerscience.go:

type computerScience struct {
numberOfProfessors int
} func (c *computerScience) getNumberOfProfessors() int {
return c.numberOfProfessors
} func (c *computerScience) getName() string {
return "computerScience"
}

数学系,mechanical.go:

type mechanical struct {
numberOfProfessors int
} func (c *mechanical) getNumberOfProfessors() int {
return c.numberOfProfessors
} func (c *mechanical) getName() string {
return "mechanical"
}

执行agency.go,输出内容如下:

Total number of professors in college1 is 9
Total number of professors in college2 is 2

End!!

GoLang设计模式12 - 空对象模式的更多相关文章

  1. 设计模式:空对象模式(Null Object Pattern)

    设计模式:空对象模式(Null Object Pattern) 背景 群里聊到<ASP.NET设计模式>,这本书里有一个“Null Object Pattern”,大家就闲聊了一下这个模式 ...

  2. C# 设计模式之空对象模式

    最近看了不少的书籍和视频等相关资料,决定自己边学习边写一下个人对设计模式的理解,如果有不对的请大家多多指正. 今天先说说我个人觉得最简单的设计模式 -- [空对象模式] 空对象模式可以减少客户端对对象 ...

  3. 设计模式之空对象模式(php实现)

    github地址:https://github.com/ZQCard/design_pattern /** * 在空对象模式(Null Object Pattern)中,一个空对象取代 NULL 对象 ...

  4. Java进阶篇设计模式之十三 ---- 观察者模式和空对象模式

    前言 在上一篇中我们学习了行为型模式的备忘录模式(Memento Pattern)和状态模式(Memento Pattern).本篇则来学习下行为型模式的最后两个模式,观察者模式(Observer P ...

  5. Java设计模式之十三 ---- 观察者模式和空对象模式

    前言 在上一篇中我们学习了行为型模式的备忘录模式(Memento Pattern)和状态模式(Memento Pattern).本篇则来学习下行为型模式的最后两个模式,观察者模式(Observer P ...

  6. 被遗忘的设计模式——空对象模式(Null Object Pattern)

    GoF(四人帮)那本<设计模式 可复用面向对象软件的基础>可谓是设计模式方面的经典之作,其中介绍的23种设计模式, 也可谓是经典中的经典.但是,设计模式的种类绝不仅仅是这23种,除此之外还 ...

  7. ASP.NET设计模式(一)、适配器模式、依赖注入依赖倒置、空对象模式

    鸟随凤鸾,人伴贤良,得以共之,我之幸也.说的是鸟随着鸾凤可以飞的更高远,人和比自己境界高的相处,自己也会得到熏染进步. 一.概述 分享出来简单的心得,望探讨 依赖倒置 依赖注入 Adapter模式 N ...

  8. 【设计模式 - 21】之空对象模式(Null Object)

    1      模式简介 在空对象模式中,一个空对象取代NULL对象的实例的检查.NULL对象不是检查空值,而是反映一个不做任何动作的关系.这样的NULL对象也可以在数据不可用的时候提供默认的行为. 在 ...

  9. 设计模式のNullObjectPattern(空对象模式)----行为模式

    一.产生背景 在空对象模式(Null Object Pattern)中,一个空对象取代 NULL 对象实例的检查.Null 对象不是检查空值,而是反应一个不做任何动作的关系.这样的 Null 对象也可 ...

随机推荐

  1. Linux系列(10) - 命令搜索命令whereis与which

    whereis 只能搜索系统命令,不能搜索自己凭空创建的普通文件 命令格式: whereis [命令名] 选项: -b:只查找可执行文件 -m:只查找帮助文件 which 搜索命令所在路径及别名:不是 ...

  2. 大型项目源码集合「GitHub 热点速览 v.21.39」

    作者:HelloGitHub-小鱼干 代码,尤其是优雅规范的代码,一直都是学习编程技巧的捷径.虽然有实用的代码小片段,能拯救当前业务的燃眉之急,但是真要去提升自己的技能还是得从大型的项目,尤其是有一定 ...

  3. 关于panic ,主协程的recover 是无法获取 子协程的panic 的

    一.子协程的panic,只能在子协程中处理 下面的代码,main 函数 无法获取panic package main import ( "fmt" "time" ...

  4. P4351-[CERC2015]Frightful Formula【组合数学,MTT】

    正题 题目链接:https://www.luogu.com.cn/problem/P4351 题目大意 \(n*n\)的矩形,给出第一行和第一列的数,剩下的满足\(F_{i,j}=a*F_{i,j-1 ...

  5. PyTorch固定参数

    In situation of finetuning, parameters in backbone network need to be frozen. To achieve this target ...

  6. yolov5实战之二维码检测

    目录 1.前沿 2.二维码数据 3.训练配置 3.1数据集设置 3.2训练参数的配置 3.3网络结构设置 3.4训练 3.5结果示例 附录:数据集下载 1.前沿 之前总结过yolov5来做皮卡丘的检测 ...

  7. FastAPI小项目实战:电影列表(Vue3 + FastAPI)

    假期过半, FastAPI + Vue3项目实战 视频也算录完了,尽管项目简单(2张表 共7个接口 4个页面) 起因 在6月底的时候开始录制了FastAPI官方文档中的新手教程部分(实际还没有官网文档 ...

  8. 峰值利用率80%+,视频云离线转码自研上云TKE实践

    作者 刘兆瑞,腾讯云高级研发工程师,负责腾讯明眸极速高清,画质重生等产品.专注于codec优化,画质增强等技术. 背景和问题 随着流量资费的降低和带宽的增加,视频成为人们获取信息越来越重要的方式,随之 ...

  9. nvidia jetson xavier 风扇开机自启动

    作者声明 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 原文链接:https://www.cnblogs.com/phoenixash/p/15 ...

  10. 解析csv数据绘制曲线图

    一个解析csv数据的小工具,所做项目中要查看脉冲图谱,经理就让我这个刚入职的小萌新写了个小程序.同事将csv格式的脉冲数据发给我,我的想法就是,将这些csv里的数据作为纵轴,x++为横轴,绘制出折线图 ...