wordpress手机站模板,网站维护需要多久时间,wordpress评论邮件回复插件,wordpress能建立大型站吗单例模式单例(Singleton)模式是设计模式之一#xff0c;最显著的特点就是一个类在一个JVM中只有一个实例#xff0c;避免繁琐的创建销毁实例。简单例子先看简单的单例模式实现完整代码#xff1a;Singleton_Test类使用单例模式 #xff0c;采用饿汉式方法。public class Si…单例模式单例(Singleton)模式是设计模式之一最显著的特点就是一个类在一个JVM中只有一个实例避免繁琐的创建销毁实例。简单例子先看简单的单例模式实现完整代码Singleton_Test类使用单例模式 采用饿汉式方法。public class Singleton_Test {private Singleton_Test() {System.out.println(私有化构造方法);}//饿汉式private static Singleton_Test Instance new Singleton_Test();public static Singleton_Test getInstance() {return Instance;}}再编写一个测试类Mainpublic class Main {public static void main(String args[]) {Singleton_Test test1 Singleton_Test.getInstance();Singleton_Test test2 Singleton_Test.getInstance();System.out.println(test1 test2);/**运行结果私有化构造方法true*/}}逐步分析1.构造方法私有化首先实现单例模式的类构造方法私有化(private)外部无法实例化(new)该类。public class Singleton_Test {private Singleton_Test(){System.out.println(私有化构造方法);}}无法实例化 Singleton_Test 类。2.私有静态类属性指向实例所以需要提供一个public static 方法 getInstance()外部通过这个方法获取对象并且由于是 实例化的同一个类所以外部每次调用都是调用同一个方法从而实现一个类只有一个实例。private static Singleton_Test Instance new Singleton_Test();//饿汉式private static Singleton_Test Instance ;//懒汉式3.使用公有静态方法返回实例返回的都是同一个类保证只实例化唯一一个类public static Singleton_Test getInstance(){return Instance;}4.测试类public static void main(String args[]) {Singleton_Test test1 Singleton_Test.getInstance();Singleton_Test test2 Singleton_Test.getInstance();System.out.println(test1 test2);/**运行结果私有化构造方法true*/}输出结果表示实例化的是同一个类并只调用一次构造方法。单例模式的实现饿汉式这种方式无论是否调用加载时都会创建一个实例。private static Singleton_Test Instance new Singleton_Test();public static Singleton_Test getInstance(){return Instance;}懒汉式这种方式是暂时不实例化在第一次调用发现为null没有指向时再实例化一个对象。private static Singleton_Test Instance ;public static Singleton_Test getInstance(){if (Instance null){Instance new Singleton_Test();}return Instance;}区别饿汉式的话是声明并创建对象(他饿)懒汉式的话只是声明对象(他懒)在调用该类的 getInstance() 方法时才会进行 new对象。饿汉式立即加载会浪费内存懒汉式延迟加载需要考虑线程安全问题 什么是线程安全/不安全饿汉式基于 classloader 机制天生实现线程安全懒汉式是线程不安全。需要加锁 (synchronized)校验等保证单例会影响效率总结构造方法私有化private Singleton_Test(){}私有静态(static)类属性指向实例private static Singleton_Test Instance使用公有静态方法返回实例public static Singleton_Test getInstance(){ return Instance;}转载自CSDN-专业IT技术社区版权声明本文为博主原创文章遵循 CC 4.0 BY-SA 版权协议转载请附上原文出处链接和本声明。