Home > Backend Development > Python Tutorial > Different implementations in different languages ​​in the singleton pattern

Different implementations in different languages ​​in the singleton pattern

coldplay.xixi
Release: 2020-10-14 17:37:20
forward
2303 people have browsed it

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!

Related labels:
source:juejin.im
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template