


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']]复制代码
m1 sons=[['s1', 's2']] m2 sons=[['s1', 's2'], ['s3', 's4']]复制代码
class Mom(object): name = '' def __init__(self): self.sons = []复制代码
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]复制代码
Singleton, and then we use it as
metaclass
class MySQLDriver: __metaclass__ = Singleton def __init__(self): print 'MySQLDriver init.....'复制代码
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 object at 0x10d848790> <__main__.MySQLDriver object at 0x10d848790> <__main__.MySQLDriver object at 0x10d848790> <__main__.MySQLDriver object at 0x10d848790>复制代码
go recently, I also want to see how to implement singleton in
go example.
type MySQLDriver struct { username string}复制代码
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 }复制代码
func main() { driver := GetDriver() driver.username = "cj" fmt.Println(driver.username) driver2 := GetDriver() fmt.Println(driver2.username) }复制代码
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 < 100; i++ { go GetDriver() } time.Sleep(2000 * time.Millisecond) }复制代码
lock.Lock()defer lock.Unlock()复制代码
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



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.

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.

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

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.

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.

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.

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.
