The examples in this article describe the differences between singleton patterns in Java and Python. Share it with everyone for your reference, the details are as follows:
Single-case mode
## The single-case mode is a commonly used software design pattern. It contains only one special class called a singleton in its core structure. The singleton pattern ensures that there is only one instance of a class in the system. That is, a class has only one object instance.
1. Singleton mode in Java/** * 单例模式 * 懒汉式 * 1)、构造器私有化 * 2)、声明私有的静态属性 * 3)、对外提供访问属性的静态方法,确保该对象存在 */ public class SingleCase { private static SingleCase sc = null; private SingleCase() { } public static SingleCase getSingleCase() { if (sc == null) { return new SingleCase(); } return sc; } } /** * 单利模式 * 饿汉式 * 1)、构造器私有化 * 2)、声明私有的静态属性,同时创建该对象 * 3)、对外提供访问属性的静态方法 * */ class SingleCase01 { private static SingleCase01 sc = new SingleCase01(); private SingleCase01() { } public static SingleCase01 getSingleCase() { return sc; } } /** * 饿汉式 * * 类在使用的时候加载 ,延缓加载时间 */ class SingleCase02 { private static class innerclass{ //内部类 private static SingleCase02 sc = new SingleCase02(); } private SingleCase02() {} public static SingleCase02 getSingleCase() { return innerclass.sc; } }
class Test(object): __instance = None __firstinit = 1 def __new__(cls, *args, **kwargs): if Test.__instance == None: Test.__instance = object.__new__(cls, *args, **kwargs) return Test.__instance def __init__(self): if not Test.__firstinit: return Test.__firstinit = 0 if __name__ == "__main__": a = Test() b = Test() print a print b
In the above example, we save the instance of the class to a class attribute __instance. Once the class attribute is not None, we will no longer call_ _new__, but directly returns __instance. In addition, in order to avoid instance initialization being performed every time Test() is called, we introduced a __firstinit class attribute. The execution result:
<__main__.Test object at 0x000002507FF6E1D0> <__main__.Test object at 0x000002507FF6E1D0>
Related recommendations:
6 of singleton mode An implementation method
Summary of single case mode and multiple case mode
The above is the detailed content of The difference between singleton pattern in Java and Python. For more information, please follow other related articles on the PHP Chinese website!