APP下载

基于图书管理场景对空对象模式的深入认识

2020-10-21汤致轩姚圣扬

科技创新与应用 2020年30期

汤致轩 姚圣扬

摘  要:在Java程序设计中,经常会遇到java.lang.NullPointerException空指针异常,在客户端总是需要判断某一对象是否为空对象,这使得客户端掌握了主动权,且程序不够友好。文章从这些常见的问题出发,分析了一个在经典的23种软件设计模式以外的模式——空对象模式,通过图书管理的场景引出问题,并合理地运用空对象模式对问题进行分析和解决,讨论了空对象模式的实现方式及应用场景,阐述了对空对象模式的优缺点分析与对软件设计模式的深入理解。

关键词:空对象模式;设计模式;特殊对象;软件工程;Java

中图分类号:TP311.52      文献标志码:A         文章编号:2095-2945(2020)30-0001-05

Abstract: In Java programming, we often encounter java.lang.NullPointerException, and in the client end, there is always need to judge whether an object is a null object, which makes the client master grasp the initiative, and the program is not friendly enough. From these common problems, this paper analyzes a pattern other than the classic 23 software design patterns-null object pattern. Through the scene of book management, some problems are pointed out. Therefore, this paper reasonably uses the null object pattern to analyze and solve the problems, discusses the realization and application scenarios of the null object pattern, and expounds the advantages and disadvantages of the null object pattern and the deep understanding of the software design pattern.

Keywords: null object pattern; design patterns; special objects; software engineering; Java

软件设计模式是一种为多数人知道、能被反复使用、并分类编目的代码设计经验的概括与总结。GoF所著《Design Patterns: Elements of Reusable Object-Oriented Software》是设计模式方面的经典之作,其中介绍了23种设计模式,但是设计模式并不止这23种,还有很多实用的软件设计模式。本文从这23种模式以外的一种设计模式——空对象模式出发,通过应用实例对空对象模式进行分析,深入挖掘此模式,阐述对此模式的理解。

在Java程序设计的过程中,经常遇到抛出空指针异常的报错信息,本文基于这种常见的问题,引入一种特殊的对象——空对象来避免这样的问题。通过使用空对象模式,对一个简单的图书管理场景进行设计,使得程序更加友好和简洁,并阐述空对象模式的实现方式及应用场景,总结空对象模式的优缺点分析与深入认识。

1 空对象模式

1.1 模式动机

在Java程序设计的……

登录APP查看全文