面試官問我, 聽說過單例模式嗎驮樊,我說聽說過薇正, 然后說讓我寫下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
正規(guī)的單例模式
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!