Table of Contents
Todaypython video tutorial column introduces different implementations of different languages ​​​​in singleton mode. " >Todaypython video tutorial column introduces different implementations of different languages ​​​​in singleton mode.
Preface
总结
Home Backend Development Python Tutorial Different implementations in different languages ​​in the singleton pattern

Different implementations in different languages ​​in the singleton pattern

Oct 13, 2020 pm 01:57 PM
python Singleton pattern

Todaypython video tutorial column introduces different implementations of different languages ​​​​in singleton mode.

Different implementations in different languages ​​in the singleton pattern

Preface

Some time ago, I discovered a pit when using Python to implement business. To be precise, it is for Python A pitfall that laymen can easily step into;

The approximate code is as follows:

class Mom(object):
    name = ''
    sons = []if __name__ == '__main__':
    m1 = Mom()
    m1.name = 'm1'
    m1.sons.append(['s1', 's2'])    print '{} sons={}'.format(m1.name, m1.sons)

    m2 = Mom()
    m2.name = 'm2'
    m2.sons.append(['s3', 's4'])    print '{} sons={}'.format(m2.name, m2.sons)复制代码
Copy after login

First defines a class of Mom, which contains a string The name of type and the sons attribute of list type;

first creates an instance of this class when using m1 and goes to ## Write a list data into #sons; then create an instance m2, and write another list data into sons.

If you are a

Javaer and rarely write Python, the first thing that comes to mind when you see this code is:

m1 sons=[['s1', 's2']]
m2 sons=[['s3', 's4']]复制代码
Copy after login
But in fact, the final output is The result is:

m1 sons=[['s1', 's2']]
m2 sons=[['s1', 's2'], ['s3', 's4']]复制代码
Copy after login
If you want to achieve the expected value, you need to modify it slightly:

class Mom(object):
    name = ''

    def __init__(self):
        self.sons = []复制代码
Copy after login
You only need to modify the definition of the class. I believe that even without

Python related experience Comparing these two codes, you should be able to guess the reason:

In

Python, if you need to use a variable as an instance variable (that is, every output we expect), you need to define the variable In the constructor, access via self.

If placed only in the class, the effect is similar to the

static static variable in Java; these data are shared by the class, which can explain why the first In this case, because the sons is shared by the Mom class, it will be accumulated every time.

Python singleton

Since

Python can achieve the effect of variables sharing in the same class through class variables, can the singleton mode be implemented?

You can use the

metaclass feature of Python to dynamically control the creation of classes.

class Singleton(type):
    _instances = {}    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)        return cls._instances[cls]复制代码
Copy after login
First create a base class of

Singleton, and then we use it as metaclass

class MySQLDriver:
    __metaclass__ = Singleton    def __init__(self):
        print 'MySQLDriver init.....'复制代码
Copy after login
in the class where we need to implement the singleton like this

Singleton can control the creation of MySQLDriver; in fact, __call__ in Singleton can easily understand the creation of this singleton Process:

    Define a dictionary of private class attributes
  • _instances (that is, map in Java) which can be done in Shared throughout the class, no matter how many instances are created.
  • When our custom class uses
  • __metaclass__ = Singleton, we can control the creation of the custom class; if an instance has been created, then directly from _instances Take out the object and return it, otherwise create an instance and write it back to _instances, which feels a bit like a Spring container.
if __name__ == '__main__':
    m1 = MySQLDriver()
    m2 = MySQLDriver()
    m3 = MySQLDriver()
    m4 = MySQLDriver()    print m1    print m2    print m3    print m4

MySQLDriver init.....
<__main__.MySQLDriver object at 0x10d848790>
<__main__.MySQLDriver object at 0x10d848790>
<__main__.MySQLDriver object at 0x10d848790>
<__main__.MySQLDriver object at 0x10d848790>复制代码
Copy after login
Finally, we can see from the experimental results that the singleton was successfully created.

Go Singleton

Since some businesses in the team have started to use

go recently, I also want to see how to implement singleton in go example.

type MySQLDriver struct {
    username string}复制代码
Copy after login
In such a simple structure (which can be simply understood as

class in Java), there is no way to be similar to Python and Java can also declare class shared variables; go There is no concept of static in the language.

But we can declare a global variable in the package to achieve the same effect:

import "fmt"type MySQLDriver struct {
    username string}var mySQLDriver *MySQLDriverfunc GetDriver() *MySQLDriver {    if mySQLDriver == nil {
        mySQLDriver = &MySQLDriver{}
    }    return mySQLDriver
}复制代码
Copy after login
In this way, when using:

func main() {
    driver := GetDriver()
    driver.username = "cj"
    fmt.Println(driver.username)

    driver2 := GetDriver()
    fmt.Println(driver2.username)

}复制代码
Copy after login
There is no need to directly construct

MySQLDriver , but obtained through the GetDriver() function. Through debug, you can also see that driver and driver1 refer to the same memory address.

Different implementations in different languages ​​in the singleton pattern

There is no problem with this kind of implementation. Smart friends will definitely think that like

Java, once concurrent access is done, it is not that simple. .

In

go, if multiple goroutine access GetDriver() at the same time, there is a high probability that multiple MySQLDriver will be created Example.

What is said here is not that simple. In fact, it is relative to

Java. The go language provides a simple api to achieve it. Access to critical resources.

var lock sync.Mutexfunc GetDriver() *MySQLDriver {
    lock.Lock()    defer lock.Unlock()    if mySQLDriver == nil {
        fmt.Println("create instance......")
        mySQLDriver = &MySQLDriver{}
    }    return mySQLDriver
}func main() {    for i := 0; i < 100; i++ {        go GetDriver()
    }

    time.Sleep(2000 * time.Millisecond)
}复制代码
Copy after login
Slightly modify the above code and add the

lock.Lock()defer lock.Unlock()复制代码
Copy after login
code to simply control access to critical resources. Even if we enable the concurrent execution of 100 coroutines,

mySQLDriver The instance will only be initialized once.

  • 这里的 defer 类似于 Java 中的 finally ,在方法调用前加上 go 关键字即可开启一个协程。

虽说能满足并发要求了,但其实这样的实现也不够优雅;仔细想想这里

mySQLDriver = &MySQLDriver{}复制代码
Copy after login

创建实例只会调用一次,但后续的每次调用都需要加锁从而带来了不必要的开销。

这样的场景每个语言都是相同的,拿 Java 来说是不是经常看到这样的单例实现:

public class Singleton {    private Singleton() {}   private volatile static Singleton instance = null;   public static Singleton getInstance() {        if (instance == null) {     
         synchronized (Singleton.class){           if (instance == null) {    
             instance = new Singleton();
               }
            }
         }        return instance;
    }
}复制代码
Copy after login

这是一个典型的双重检查的单例,这里做了两次检查便可以避免后续其他线程再次访问锁。

同样的对于 go 来说也类似:

func GetDriver() *MySQLDriver {    if mySQLDriver == nil {
        lock.Lock()        defer lock.Unlock()        if mySQLDriver == nil {
            fmt.Println("create instance......")
            mySQLDriver = &MySQLDriver{}
        }
    }    return mySQLDriver
}复制代码
Copy after login

Java 一样,在原有基础上额外做一次判断也能达到同样的效果。

但有没有觉得这样的代码非常繁琐,这一点 go 提供的 api 就非常省事了:

var once sync.Oncefunc GetDriver() *MySQLDriver {
    once.Do(func() {        if mySQLDriver == nil {
            fmt.Println("create instance......")
            mySQLDriver = &MySQLDriver{}
        }
    })    return mySQLDriver
}复制代码
Copy after login

本质上我们只需要不管在什么情况下  MySQLDriver 实例只初始化一次就能达到单例的目的,所以利用 once.Do() 就能让代码只执行一次。

Different implementations in different languages ​​in the singleton pattern

查看源码会发现 once.Do() 也是通过锁来实现,只是在加锁之前利用底层的原子操作做了一次校验,从而避免每次都要加锁,性能会更好。

总结

相信大家日常开发中很少会碰到需要自己实现一个单例;首先大部分情况下我们都不需要单例,即使是需要,框架通常也都有集成。

类似于 go 这样框架较少,需要我们自己实现时其实也不需要过多考虑并发的问题;摸摸自己肚子左上方的位置想想,自己写的这个对象真的同时有几百上千的并发来创建嘛?

不过通过这个对比会发现 go 的语法确实要比 Java 简洁太多,同时轻量级的协程以及简单易用的并发工具支持看起来都要比 Java 优雅许多;后续有机会再接着深入。

相关免费学习推荐:python视频教程

The above is the detailed content of Different implementations in different languages ​​in the singleton pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

Can vscode run ipynb Can vscode run ipynb Apr 15, 2025 pm 07:30 PM

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.

See all articles