search
HomeBackend DevelopmentPython TutorialDifferent implementations in different languages ​​in the 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)复制代码

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']]复制代码
But in fact, the final output is The result is:

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

class Mom(object):
    name = ''

    def __init__(self):
        self.sons = []复制代码
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]复制代码
First create a base class of

Singleton, and then we use it as metaclass

class MySQLDriver:
    __metaclass__ = Singleton    def __init__(self):
        print 'MySQLDriver init.....'复制代码
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>
<__main__.mysqldriver>
<__main__.mysqldriver>
<__main__.mysqldriver>复制代码</__main__.mysqldriver></__main__.mysqldriver></__main__.mysqldriver></__main__.mysqldriver>
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}复制代码
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
}复制代码
In this way, when using:

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

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

}复制代码
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 Slightly modify the above code and add the <p></p><pre class="brush:php;toolbar:false">lock.Lock()defer lock.Unlock()复制代码
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{}复制代码

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

这样的场景每个语言都是相同的,拿 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;
    }
}复制代码

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

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

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

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

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

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

本质上我们只需要不管在什么情况下  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
This article is reproduced at:juejin. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools