


Different implementations in different languages in the singleton pattern
Todaypython video tutorial column introduces different implementations of different languages in singleton mode.
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.
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:
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.
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 can achieve the effect of variables sharing in the same class through class variables, can the singleton mode be implemented?
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,
mapin
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
_instancesTake out the object and return it, otherwise create an instance and write it back to
_instances, which feels a bit like a
Springcontainer.
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 SingletonSince 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.
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.
Java, once concurrent access is done, it is not that simple. .
go, if multiple
goroutine access
GetDriver() at the same time, there is a high probability that multiple
MySQLDriver will be created Example.
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()
就能让代码只执行一次。
查看源码会发现 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!

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.

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.

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.

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.

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 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.

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 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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools