设计模式之牛刀小试(读取配置文件)

# conf.py

import os
import sys
import inspect
from abc import ABCMeta, abstractmethod



class ConfBase(metaclass=ABCMeta):
    @abstractmethod
    def read(self):
        pass

    def print(self):
        print(self.__class__)



class YamlReader(ConfBase):
    def __init__(self, path):
        self.path = path

    def read(self):
        # todo: Read Yaml file ...

        ret_d = dict()
        ret_d["j"] = "JsonReaderClass"
        ret_d["y"] = "YamlReaderClass"
        return ret_d



class JsonReader(ConfBase):
    def __init__(self, path):
        self.path = path

    def read(self):
        # todo: Read Json file ...

        ret_d = dict()
        ret_d["j"] = "JsonReaderClass"
        ret_d["y"] = "YamlReaderClass"
        return ret_d



class FactoryMethod:
    def __init__(self, filepath):
        self.filepath = filepath
        self.obj = None

    def get_obj(self):
        suffix = os.path.splitext(self.filepath)[-1]
        suffix = suffix.lstrip(".").lower().capitalize()
        for name, cls in inspect.getmembers(sys.modules[__name__]):
            if inspect.isclass(cls):
                if suffix in cls.__name__:
                    self.obj = cls(self.filepath)
                    break
        return self.obj
# settings.py

from pyScripts.lib import conf



class Settings:
    def __init__(self, filepath):
        self.filepath = filepath
        self.tmp_d = None

    def parse_file(self):
        f = conf.FactoryMethod(self.filepath)
        obj = f.get_obj()
        self.tmp_d = obj.read()

    def set_field(self):
        self.A = self.tmp_d["j"]

    def read(self):
        self.parse_file()
        self.set_field()



if __name__ == '__main__':
    path = "abc.json"
    s = Settings(path)
    s.read()
    print(s.A)
    pass

posted @ 2022-08-11 10:31  道友请留步W  阅读(36)  评论(1编辑  收藏  举报