美文网首页
Python-Python实现单例模式

Python-Python实现单例模式

作者: yunpiao | 来源:发表于2018-07-21 17:07 被阅读0次

    面试官问我, 听说过单例模式吗,我说听说过, 然后说让我写下Python的单例模式。然后我就懵逼了。 之前看过, 因为没有记录, 忘的嘎嘣脆。。。

    Python中一切皆对象。

    最简单的单例模式

    class Class_A(object):
        print("single_model")
        
    def single_instance():
        return Class_A
    
    print(id(single_instance()))
    print(id(single_instance()))
    
    single_model
    94873513761768
    94873513761768
    

    正规的单例模式

    class Singleton(object):
        _instance = None
        def __new__(self, *args, **kwargs):
            if self._instance is None:
                self._instance = object.__new__(self, *args, **kwargs)
    
            return self._instance
    
    s1 = Singleton()
    s2 = Singleton()
    print(id(s1))
    print(id(s2))
    
    
    139693198402056
    139693198402056
    

    工厂模式

    class Fruit(object):
        def __init__(self):
            pass
    
        def print_color(self):
            print("I do not know!")
    
    class Apple(Fruit):
        def __init__(self):
            pass
    
        def print_color(self):
            print("apple is in red")
    
    class Orange(Fruit):
        def __init__(self):
            pass
    
        def print_color(self):
            print("orange is in orange")
    
    class FruitFactory(object):
        fruits = {"apple": Apple, "orange": Orange}
    
        def __new__(self, name):
            if name in self.fruits.keys():
                print(name)
                return self.fruits[name]()
            else:
                return Fruit()
            
    fruit1 = FruitFactory("apple")
    fruit2 = FruitFactory("orange")
    fruit3 = FruitFactory("fruit")
    
    fruit1.print_color()    
    fruit2.print_color()    
    fruit3.print_color()    
    
    apple
    orange
    apple is in red
    orange is in orange
    I do not know!
    

    总结, 一直一来都没有好好总结用过的知识, 结果现在忘性越来越大,以后要保持每天一篇文章。(😏水也要水一篇)

    相关文章

      网友评论

          本文标题:Python-Python实现单例模式

          本文链接:https://www.haomeiwen.com/subject/jruhmftx.html