所谓单例,是指一个类的实例从始至终只能被创建一次。
方法1
使用类在初始化时候被实例
1 class NBSite(object): 2 def __init__(self): 3 self.name = 'nb' 4 self.namespace = 'nb' 5 self._registry= {} 6 def register(self,model,model_nb=None): 7 if not model_nb: 8 model_nb=ModelNB 9 self._registry[model]=model_nb(model,self)10 print(self._registry)11 def login(self,request):12 return HttpResponse('登陆页面')13 def logout(self,request):14 return HttpResponse('注销页面')15 16 17 def get_urls(self):18 patterns=[]19 from django.conf.urls import url20 patterns +=[21 url(r'^login/',self.login),22 url(r'^logout/',self.logout),23 ]24 for model_class,model_nb_obj in self._registry.items():25 patterns +=[26 url(r'^%s/%s/' %(model_class._meta.app_label,model_class._meta.model_name,),27 model_nb_obj.urls)]28 return patterns29 @property30 def urls(self):31 return self.get_urls(),self.name,self.namespace32 33 site=NBSite()