设计模式

9 篇文章 0 订阅

单例模式

Python

  1. #参考:http://ghostfromheaven.iteye.com/blog/1562618
  2. #使用装饰器(decorator),  
  3. #这是一种更pythonic,更elegant的方法,  
  4. #单例类本身根本不知道自己是单例的,因为他本身(自己的代码)并不是单例的  
  5. def singleton(cls, *args, **kw):  
  6.     instances = {}  
  7.     def _singleton():  
  8.         if cls not in instances:  
  9.             instances[cls] = cls(*args, **kw)  
  10.         return instances[cls]  
  11.     return _singleton  
  12.  
  13. @singleton  
  14. class MyClass4(object):  
  15.     a = 1  
  16.     def __init__(self, x=0):  
  17.         self.x = x  
  18.   
  19. one = MyClass4()  
  20. two = MyClass4()  
  21.   
  22. two.a = 3  
  23. print one.a  
  24. #3  
  25. print id(one)  
  26. #29660784  
  27. print id(two)  
  28. #29660784  
  29. print one == two  
  30. #True  
  31. print one is two  
  32. #True  
  33. one.x = 1  
  34. print one.x  
  35. #1  
  36. print two.x  
  37. #1  

Java

public class Singleton {  
    private static class SingletonHolder {  
    private static final Singleton INSTANCE = new Singleton();  
    }  
    private Singleton (){}  
    public static final Singleton getInstance() {  
    return SingletonHolder.INSTANCE;  
    }  
} 
=======
public enum Singleton {  
    INSTANCE;  
    public void whateverMethod() {  
    }  
} 


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值