面试官问我, 听说过单例模式吗,我说听说过, 然后说让我写下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!