python学习系列:python的单体模式实现


最近实现了一个单体模式,来处理一个基于JSON数据结构的任务,发出来希望高手指点。

代码片段

# -*-coding:utf-8-*-
# version:0.2
# 重构,以方便实现在table中增加一行的功能
# simple task manager
import sys
import json

"""
为Task单独实现一个类,这个类就是用来存储数据的,并且只有一份,也就是单体模式;
"""
class TasksSingleton(object):
    _instance = None
    _taskJson = None
    _taskFileName = None

 """为了实现单体的方法,继承object类,重构其__new__函数"""
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls.loadFile()
        return cls._instance

"""获得当前应该使用的task数据,例如9月份的数据为task9.json"""
    @staticmethod
    def getFileName():
        return "./taskdata/tasks9.json"

"""将文件系统中的jason文件,导入到TasksSingleton类的_taskJson参数中"""
    @staticmethod
    def loadFile():
        try:
            global _taskFileName
            _taskFileName = TasksSingleton.getFileName()
            taskfile = open(_taskFileName, rb)
            global _taskJson
            _taskJson = json.load(taskfile)
            taskfile.close()
        except FileNotFoundError:
            print("task json file not found.")
            sys.exit()

"""将_taskJson中的数据,存储到对应月份的文件中,例如9月份就存储到tasks9.json"""
    @staticmethod
    def saveFile():
        try:
            global _taskFileName
            global _taskJson
            taskfile = open(_taskFileName, w)
            json.dump(_taskJson, taskfile)
            taskfile.close()
        except FileNotFoundError:
            print("task json file not found.")
            sys.exit()

"""可以不对外体现,我们只需要体现几个操作_taskJson值的函数就可以了"""
    @staticmethod
    def getTaskJson():
        global _taskJson
        return _taskJson

"""得到Task表单的表头"""
    @staticmethod
    def getTasksHeaders():
        global _taskJson
        return _taskJson["headers"]

"""得到Task的具体内容,有多少行返回多少行,如果为空,返回None"""
    @staticmethod
    def getTasksRows():
        global _taskJson
        tasksRows = _taskJson["tasks"]
        if len(tasksRows)>0:
            return tasksRows
        else:
            return None

"""将task列表中(i,j)对应的值修改成传入的参数item"""
    @staticmethod
    def setTaskItem(i, j, item):
        global _taskJson
        tasksRows = _taskJson["tasks"]
        if -1 < i < len(tasksRows) and -1 < j < len(_taskJson["headers"]):
            tasksRows[i][j] = item
            return True
        else:
            return False

"""在数据中插入一列新的任务"""
    @staticmethod
    def insertOneTask(taskContent, deadline):
        newTask = [taskContent, "", "", deadline, ""]
        print("insert row:", newTask)
        global _taskJson
        tasksRows = _taskJson["tasks"]
        tasksRows.append(newTask)
        print(_taskJson)
        pass


"""
    感觉没有用,反而将程序变复杂了,我先按照没用来处理,看后续学习单体模式以后,再理解
    为Task单独实现一个类,这个类就是用来存储数据的,并且只有一份,也就是单体模式
"""
class Tasks(object):
    __metaclass__ = TasksSingleton()

    @staticmethod
    def getfilename():
        print("file is here.")

疑问

在网上搜到说,python的单体模式,要在一个单体结构中实现__new__(cls)函数,而后实现一个类,其metaclass要初始化为这个单体的实例; 但是我实现的时候,感觉后边这个类没什么用,不知道是否理解有误。

经验分享 程序员 微信小程序 职场和发展