python装饰器实现单例模式

1、闭包的实现

[python]  view plain  copy
  1. #coding:utf-8  
[python]  view plain  copy
  1. def A():  
  2.     s1=2  
  3.     def B():  
  4.         sum1=s1+2  
  5.         return sum1  
  6.     return B  
  7.   
  8. if __name__ == '__main__':  
  9.     f1=A()  
  10.     f2=f1()  
  11.     print 'f1: ',f1  
  12.     print 'f2: ',f2  
[python]  view plain  copy
  1. 输出:  
[python]  view plain  copy
  1. f1:  <function B at 0x02BDEB30>  
  2. f2:  4  

可以看出f1为一个函数,调用这个函数时,才会返回值

闭包可以使得内函数返回的局部变量的生命周期与整个项目相同,即sum1会一直保留到整个工程运行结束,而不是这个函数执行完。

2、python 装饰器

[python]  view plain  copy
  1. def fun1(fun):  
  2.     print 'fun1 action'  
  3.     return fun  
  4.  
  5. @fun1      
  6. def fun2():  
  7.     print 'fun2 action'  
  8.       
  9. if __name__ == '__main__':  
  10.     fun2()  
[python]  view plain  copy
  1. 输出:  
[python]  view plain  copy
  1. fun1 action  
  2. fun2 action  
@fun1的功能:实际上是将fun2作为参数传递fun1再进行执行

3、装饰器+闭包实现单例模式

单例模式:顾名思义,一个类,在整个项目的运行周期内只有一个实例

实现:

[python]  view plain  copy
  1. def singleton(cls, *args, **kw):  
  2.     instance={}  
  3.     def _singleton():  
  4.         if cls not in instance:  
  5.             instance[cls]=cls(*args, **kw)  
  6.         return instance[cls]  
  7.     return _singleton  
  8.  
  9. @singleton  
  10. class test_singleton(object):  
  11.     def __init__(self):  
  12.         self.num_sum=0  
  13.     def add(self):  
  14.         self.num_sum=100  
[python]  view plain  copy
  1. 输出:  
[python]  view plain  copy
  1. <__main__.test_singleton object at 0x023F6AD0>  
  2. <__main__.test_singleton object at 0x023F6AD0>  
可以看出,虽然进行了两次实例化,但仍为同一个实例
不使用单例模式时:

[python]  view plain  copy
  1. class test_singleton(object):  
  2.     def __init__(self):  
  3.         self.num_sum=0  
  4.     def add(self):  
  5.         self.num_sum=100  
  6.       
  7. if __name__ == '__main__':  
  8.     cls1= test_singleton()  
  9.     cls2= test_singleton()  
  10.     print cls1  
  11.     print cls2  
[python]  view plain  copy
  1. 输出:  
[python]  view plain  copy
  1. <__main__.test_singleton object at 0x022569F0>  
  2. <__main__.test_singleton object at 0x02256A10>  
显然,此时为两个不同的实例

至于单例模式在python中的作用,我第一次使用,是因为传参传了太多层,以至于我找不到参数是哪里来的了(传参为类),可是如果把传的参数设置成单例模式,便可以直接在程序中直接使用该类的成员变量,通过类名().变量名的形式,而不需要再进行参数传递,数据是从哪里来的,也一目了然,感觉比较方便。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值