go单例模式和饿汉模式
时间: 2024-06-17 15:03:28 浏览: 16
Go语言中的单例模式和其他语言的单例模式一样,都是保证一个类只有一个实例,并提供全局访问点。
在Go语言中,实现单例模式主要有两种方式:懒汉模式和饿汉模式。
1. 懒汉模式:
懒汉模式是指在第一次调用获取实例方法时才会创建实例,这种方式实现比较简单,但是需要注意并发访问时的线程安全问题。
2. 饿汉模式:
饿汉模式是指在程序启动时就创建实例,这样可以保证线程安全,但是可能会浪费系统资源。
下面是一个简单的Go语言实现的饿汉单例模式示例:
```
package singleton
type Singleton struct{}
var instance *Singleton
func init() {
instance = &Singleton{}
}
func GetInstance() *Singleton {
return instance
}
```
在该示例中,init()函数在程序启动时就会执行,创建了Singleton的唯一实例instance。GetInstance()函数返回该唯一实例。
相关问题
懒汉式单例模式和饿汉式单例模式的异同
以下是懒汉式单例模式和饿汉式单例模式的异同:
相同点:
1. 都是单例模式,即保证一个类只有一个实例对象。
2. 都使用了私有的构造函数,防止外部创建实例对象。
3. 都使用了静态变量来保存实例对象。
不同点:
1. 创建对象的时机不同:饿汉式在类加载时就创建了对象实例,而懒汉式是在使用时才创建。
2. 线程安全性不同:饿汉式天生是线程安全的,因为在类加载时就已经创建了对象实例,而懒汉式需要考虑线程安全问题,可以使用synchronized关键字或者双重检查锁定等方式来保证线程安全。
3. 性能不同:饿汉式在类加载时就创建了对象实例,所以在访问速度和反应时间上都比懒汉式快,但是如果这个实例一直没有被使用,那么就会造成内存浪费。而懒汉式只有在使用时才会创建对象实例,所以在内存占用上比饿汉式要低,但是在访问速度和反应时间上会稍微慢一些。
下面是懒汉式单例模式的示例代码:
```python
class Singleton:
__instance = None
def __init__(self):
if Singleton.__instance != None:
raise Exception("该类已经实例化过了")
else:
Singleton.__instance = self
@staticmethod
def getInstance():
if Singleton.__instance == None:
Singleton()
return Singleton.__instance
```
下面是饿汉式单例模式的示例代码:
```python
class Singleton:
__instance = Singleton()
def __init__(self):
if Singleton.__instance != None:
raise Exception("该类已经实例化过了")
else:
Singleton.__instance = self
@staticmethod
def getInstance():
return Singleton.__instance
```
使用懒汉单例模式和饿汉单例模式模拟产生本班的班长
可以使用懒汉单例模式和饿汉单例模式来模拟产生本班的班长。懒汉单例模式是在需要时才创建实例,而饿汉单例模式是在类加载时就创建实例。以下是懒汉单例模式和饿汉单例模式的示例代码:
懒汉单例模式:
```
public class ClassPresident {
private static ClassPresident instance;
private ClassPresident() {}
public static synchronized ClassPresident getInstance() {
if (instance == null) {
instance = new ClassPresident();
}
return instance;
}
}
```
饿汉单例模式:
```
public class ClassPresident {
private static ClassPresident instance = new ClassPresident();
private ClassPresident() {}
public static ClassPresident getInstance() {
return instance;
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)