Java写单例设计模式
时间: 2023-04-02 17:00:31 浏览: 230
单例设计模式是一种常用的设计模式,它可以保证一个类只有一个实例,并提供一个全局访问点。在 Java 中,可以通过私有构造函数和静态方法来实现单例模式。具体实现方式可以参考以下代码:
public class Singleton {
private static Singleton instance = null;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
在这个实现中,私有构造函数保证了外部无法直接创建实例,而静态方法 getInstance() 则提供了全局访问点,确保只有一个实例被创建。
相关问题
java实现单例设计模式居民身份证
Java实现单例设计模式有多种方式,其中比较常用的是饿汉式和懒汉式。
1. 饿汉式:
饿汉式是指在类加载时就创建实例对象,保证了线程安全。具体实现如下:
```java
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
// 私有构造方法
}
public static Singleton getInstance() {
return instance;
}
}
```
在上述代码中,私有的构造方法保证了其他类无法直接实例化该类,而静态的getInstance()方法返回了唯一的实例对象。
2. 懒汉式:
懒汉式是指在需要使用实例对象时才进行创建,可以节省资源。但需要注意线程安全问题,可以通过加锁或双重检查锁定来解决。以下是双重检查锁定的实现方式:
```java
public class Singleton {
private volatile static Singleton instance;
private Singleton() {
// 私有构造方法
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
```
在上述代码中,使用了volatile关键字来保证instance的可见性,双重检查锁定确保了只有在instance为null时才创建实例对象。
java单例设计模式练习题
在Java中,单例设计模式是一种常用的软件设计模式,用于确保一个类只有一个实例,并提供一个全局访问点。这是一种创建型模式,主要用于限制系统资源的创建数量,或者为对象提供统一的行为。
下面是一个简单的Java单例模式实现(懒汉式和饿汉式)练习题示例:
**1. 懒汉式单例(线程不安全):**
```java
public class LazySingleton {
private LazySingleton() {}
public static synchronized LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
```