java单例设计模式
单例字典的含义:正在考虑的单一的人或事物。
Java单例设计模式被认为是最简单的设计模式之一。它属于创意设计模式类别。
Singleton设计模式仅声明应仅创建单个对象,并且它将被所有其他类使用。
单例设计模式通常用于日志记录、缓存、驱动程序对象、线程池等。它也用于其他设计模式,如抽象工厂、立面、构建器、原型等。
如何创建单例设计模式?
单例设计模式可以以不同的方式实现,但概念对所有人都是一样的。
- 私有构造函数: 私有构造函数用于防止从其他类实例化类。
- 私有静态变量: 私有静态变量将包含类的实例。
- 公共静态方法: 公共静态方法是其他类获取单例类实例的全局访问点。它将返回singleton类的实例。
让我们讨论用不同的方法实现单例设计模式。
急切的初始化
如果渴望初始化,则在类加载时创建singleton类的实例。
示例:
package com.codesjava;public class SingletonTest {private static final SingletonTest instance = new SingletonTest();//Private constructor to prevent instantiation of the class from other classes.private SingletonTest() {}public static SingletonTest getInstance() {return instance;}}
急切初始化方法的问题:
正如我们所讨论的,singleton类的实例是在类加载时创建的。因此,可能存在客户端应用程序不使用对象但仍创建对象的情况。急切初始化方法的另一个问题是我们没有任何方法来处理异常。
静态块初始化
实现单例设计模式的静态块初始化方法与具有异常处理功能的急切初始化方法几乎相同。
示例:
package com.codesjava;public class SingletonTest {private static final SingletonTest instance;//Private constructor to prevent instantiation of the class from other classes.private SingletonTest() {}//Static block initializationstatic {try {instance = new SingletonTest();} catch(Exception e) {throw new RuntimeException("Exception occured.");}}public static SingletonTest getInstance() {return instance;}}
静态块初始化方法的问题:
它用急切的初始化方法解决了异常处理问题,但是在使用它之前的对象创建仍然存在。
延迟初始化
实现单例设计模式的惰性初始化方法解决了在使用对象之前创建对象的问题。在这种方法中,我们将在全局访问方法中创建实例。
示例:
package com.codesjava;public class SingletonTest {private static SingletonTest instance;//Private constructor to prevent instantiation of the class from other classes.private SingletonTest() {}public static SingletonTest getInstance() {if (instance == null) {instance = new SingletonTest();}return instance;}}
延迟初始化方法的问题:
延迟初始化方法可能不起作用,并可能在多线程环境中引起问题。如我们所见,getInstance() 方法没有锁,因此如果两个线程正在访问getInstance() 方法同时,他们可以得到两个不同的对象,这将打破单例概念。
线程安全方法
实现单例设计模式的线程安全方法将解决多线程问题。我们必须创建一个线程安全的单例类,为此我们可以创建全局访问方法。在这种情况下,当一个线程执行getInstance() 方法时,其他线程必须等待。我们也可以使用同步块,这是一个更好的选择。
同步方法示例
package com.codesjava;public class SingletonTest {private static SingletonTest instance;//Private constructor to prevent instantiation of the class from other classes.private SingletonTest() {}public static synchronized SingletonTest getInstance() {if (instance == null) {instance = new SingletonTest();}return instance;}}
具有同步块的示例
package com.codesjava;public class SingletonTest {private static SingletonTest instance;//Private constructor to prevent instantiation of the class from other classes.private SingletonTest() {}//Synchronized block with double checked locking principlepublic static SingletonTest getInstance() {if (instance == null) {synchronized (SingletonTest.class) {if(instance == null){instance = new SingletonTest();}}}return instance;}}
Bill Pugh单例实施
它是实现单例设计模式的最广泛使用的方法。它使用私有内部静态帮助程序类创建单例类。内部静态类将包含singleton类对象。它不会加载singleton类,它将在第一次调用getInstance() 方法时加载。
注意: Bill Pugh单例实现方法不需要同步。
示例:
package com.codesjava;public class SingletonTest {//Private constructor to prevent instantiation of the class from other classes.private SingletonTest() {}private static class SingletonHelper {private static final SingletonTest INSTANCE = new SingletonTest();}public static SingletonTest getInstance() {return SingletonHelper.INSTANCE;}}
使用反射破坏单例模式
根据Java文档: 反射使Java代码能够发现有关加载类的字段、方法和构造函数的信息,并使用反射字段、方法和构造函数对其底层对应项进行操作,在安全限制范围内。
我们可以使用反射来破坏上述所有方法来实现单例设计模式。
示例:
package com.codesjava;import java.lang.reflect.Constructor;class SingletonTest {private static final SingletonTest instance = new SingletonTest();//Private constructor to prevent instantiation of the class from other classes.private SingletonTest() {}public static SingletonTest getInstance() {return instance;}}public class SingletonTestWithReflection {public static void main(String[] args) {SingletonTest instance1 = SingletonTest.getInstance();SingletonTest instance2 = null;try {Constructor[] constructors = SingletonTest.class.getDeclaredConstructors();for (Constructor constructor : constructors) {constructor.setAccessible(true);instance2 = (SingletonTest) constructor.newInstance();break;}} catch (Exception e) {e.printStackTrace();}System.out.println(instance1.hashCode());System.out.println(instance2.hashCode());}}
输出:
3667126421829164700
注意: 您可以清楚地看到两个对象的哈希代码是不同的,这打破了单例设计模式的概念。为了克服这个问题,我们应该使用枚举来实现单例设计模式,因为枚举值只实例化一次。
单例设计模式中的序列化
我们可以序列化一个单例对象,但是在反序列化的情况下,它将返回一个新对象,这将破坏单例设计模式的概念。为了克服这个问题,我们需要提供Readparse () 方法这加强了单例模式。
package com.codesjava;import java.io.Serializable;public class SingletonTest implements Serializable {//Private constructor to prevent instantiation of the class from other classes.private SingletonTest() {}private static class SingletonHelper {private static final SingletonTest INSTANCE = new SingletonTest();}public static SingletonTest getInstance() {return SingletonHelper.INSTANCE;}protected Object readResolve() {return getInstance();}}
java原型设计模式
字典原型的含义:开发其他形式的设备或车辆的第一个或初步版本。
Java原型设计模式属于创建设计模式类别,它用于创建新对象成本高的情况。
Java原型设计模式指出,如果创建新对象的成本比克隆原始对象然后对其进行修改 (而不是创建新对象) 要高。
让我们想象一下,我们有一个从数据库加载的客户对象,加载后我们必须多次修改其数据。在这种情况下,我们必须克隆该对象,而不是创建新对象并再次从数据库加载所有数据。
示例
客户。java
package com.codesjava;import java.util.ArrayList;import java.util.List;public class Customers implements Cloneable {private List<String> customerList;public Customers() {customerList = new ArrayList<String>();}public Customers(List<String> list) {this.customerList=list;}public void loadDataFromDB() {//Read all customers from DBcustomerList.add("Bharat");customerList.add("Sahdev");customerList.add("Richi");customerList.add("Jai");customerList.add("Bharti");customerList.add("Saveta");customerList.add("Deepika");}public List<String> getCustomerList() {return customerList;}@Overridepublic Object clone() throws CloneNotSupportedException {List<String> temp = new ArrayList<String>();for (String string : this.getCustomerList()) {temp.add(string);}return new Customers(temp);}}
原型模式测试
package com.codesjava;import java.util.List;public class PrototypePatternTest {public static void main(String args[]) {try {Customers customers = new Customers();customers.loadDataFromDB();Customers customers1 = (Customers) customers.clone();Customers customers2 = (Customers) customers.clone();List<String> customersList1 = customers1.getCustomerList();customersList1.add("Vivek");List<String> customersList2 = customers2.getCustomerList();customersList2.remove("Deepika");System.out.println("customers List elements: " + customers.getCustomerList());System.out.println("customers1 List elements: " + customersList1);System.out.println("customers2 List elements: " + customersList2);} catch (CloneNotSupportedException e) {e.printStackTrace();}}}
输出
customers List elements: [Bharat, Sahdev, Richi, Jai, Bharti, Saveta, Deepika]customers1 List elements: [Bharat, Sahdev, Richi, Jai, Bharti, Saveta, Deepika, Vivek]customers2 List elements: [Bharat, Sahdev, Richi, Jai, Bharti, Saveta]
