本篇内容介绍了“java反射与单例设计模式实例介绍”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
创新互联专注于鲁甸网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供鲁甸营销型网站建设,鲁甸网站制作、鲁甸网页设计、鲁甸网站官网定制、微信小程序定制开发服务,打造鲁甸网络公司原创品牌,更为您提供鲁甸网站排名全网营销落地服务。
反射与单例设计模式
单例设计模式的核心本质在于:类内部的构造方法私有化,在类的内部产生实例化对象后通过static方法获取实例化对象,进行类中的结构调用,单例设计模式一共有两类:懒汉式、饿汉式,本节主要来讨论懒汉式的单例设计模式。
范例:观察懒汉式单例设计模式的问题
单线程状态执行:
public class JavaAPIDemo {
public static void main(String[] args) throws Exception {
Singleton sinA = Singleton.getInstance();
sinA.print();
}
}
class Singleton {
private static Singleton instance = null;
private Singleton() {}
public static Singleton getInstance() {if (instance == null) { instance = new Singleton();
}
return instance; }
public void print() {
System.out.println("www.mldn.cn");
}
}多线程状态执行:
public class JavaAPIDemo {
public static void main(String[] args) throws Exception {for (int x = 0; x < 3; x++) {new Thread(()->{
Singleton.getInstance().print();
},"单例消费端-"+ x).start();
}/** * 【单例消费端-0】****** 实例化Singleton类对象 ******* * 【单例消费端-1】****** 实例化Singleton类对象 ******* * www.mldn.cn * 【单例消费端-2】****** 实例化Singleton类对象 ******* * www.mldn.cn * www.mldn.cn */}
}class Singleton {
private static Singleton instance = null;
private Singleton() {
System.out.println("【" + Thread.currentThread().getName() +"】****** 实例化Singleton类对象 *******",Thread.currentThread().getName());
}
public static Singleton getInstance() {if (instance == null) {
instance = new Singleton();
}return instance;
}
public void print() {
System.out.println("www.mldn.cn");
}
}单例设计模式的最大特点是在整体的运行程序中只允许产生一个实例化对象,但当有了若干个线程之后,实际上当前的程序就会产生多个实例化对象了,此时就不是单例设计模式了。此时问题造成的关键在于代码本身出现了不同步的情况,而要想解决的关键就在于同步处理,也就是需要使用synchronized关键字。

单例设计模式问题
范例:修改getInstance()进行同步处理
class Singleton {
private static Singleton instance = null;
private Singleton() {
System.out.println("【" + Thread.currentThread().getName() +"】****** 实例化Singleton类对象 *******",Thread.currentThread().getName());
}
public static synchronized Singleton getInstance() {if (instance == null) { instance = new Singleton();
}
return instance; }
public void print() {
System.out.println("www.mldn.cn");
}
}这个时候的确是进行了同步处理,但这个同步处理的代价有些大,因为效率会低。因为整体代码中实际上只有一块部分需要进行同步处理,也就是instance对象的实例化处理部分。我们可以知道,之前的同步操作是有些失误的。
范例:更加合理地进行同步处理
class Singleton {
private static volatile Singleton instance = null;
private Singleton() {
System.out.printf("【" + Thread.currentThread().getName() +"】****** 实例化Singleton类对象 *******",Thread.currentThread().getName());
}
public static Singleton getInstance() {if (instance == null) {
synchronized (Singleton.class) {if (instance == null) { instance = new Singleton();
}
}
}
return instance; }
public void print() {
System.out.println("www.mldn.cn");
}
}“java反射与单例设计模式实例介绍”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注创新互联网站,小编将为大家输出更多高质量的实用文章!
网站名称:java反射与单例设计模式实例介绍
网页URL:http://www.jxjierui.cn/article/ijgohh.html


咨询
建站咨询
