Java单例模式的终结者
发布日期:2021-06-30 11:12:44 浏览次数:3 分类:技术文章

本文共 2666 字,大约阅读时间需要 8 分钟。


版权声明

  • 本文原创作者:谷哥的小弟
  • 作者博客地址:http://blog.csdn.net/lfdfhl

概述

我们都知道:单例模式的核心在于通过该类只能创建一个对象;就算多次创建所获得的对象均是同一个。有没有办法让一个单例类创建出不同的对象呢?答案是肯定的。今天,我们就来通过反射技术终结单例模式!

单例模式回顾

我们先来回顾一下单例模式。

代码如下:

package com.singleton4;/** * 本文作者:谷哥的小弟  * 博客地址:http://blog.csdn.net/lfdfhl * 示例描述:单例设计模式之懒汉式 */public class SingletonInstance {
private static SingletonInstance instance = null; private SingletonInstance() {
} public static synchronized SingletonInstance getInstance() {
if (instance == null) {
instance = new SingletonInstance(); } return instance; }}

测试代码:

package com.singleton4;import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;/*** 本文作者:谷哥的小弟 * 博客地址:http://blog.csdn.net/lfdfhl* 示例描述:利用反射技术破坏单例模式*/public class SingletonDemo {
public static void main(String[] args) {
testSingleton1(); } public static void testSingleton1() {
SingletonInstance instance1 = SingletonInstance.getInstance(); SingletonInstance instance2 = SingletonInstance.getInstance(); System.out.println(instance1); System.out.println(instance2); System.out.println(instance1==instance2); }}

结果如下:

在这里插入图片描述

反射技术与单例模式

接下来,我们使用反射技术终结单例模式。

代码如下:

package com.singleton4;import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;/*** 本文作者:谷哥的小弟 * 博客地址:http://blog.csdn.net/lfdfhl* 示例描述:利用反射技术破坏单例模式*/public class SingletonDemo {
public static void main(String[] args) {
testSingleton2(); } public static void testSingleton1() {
SingletonInstance instance1 = SingletonInstance.getInstance(); SingletonInstance instance2 = SingletonInstance.getInstance(); System.out.println(instance1); System.out.println(instance2); System.out.println(instance1==instance2); } public static void testSingleton2() {
Class
clazz=SingletonInstance.class; try {
// 获取私有构造函数 Constructor
declaredConstructor = clazz.getDeclaredConstructor(); // 取消安全性检查 declaredConstructor.setAccessible(true); try {
// 创建对象 SingletonInstance instance1 = declaredConstructor.newInstance(); SingletonInstance instance2 = declaredConstructor.newInstance(); System.out.println(instance1); System.out.println(instance2); System.out.println(instance1==instance2); } catch (InstantiationException e) {
e.printStackTrace(); } catch (IllegalAccessException e) {
e.printStackTrace(); } catch (IllegalArgumentException e) {
e.printStackTrace(); } catch (InvocationTargetException e) {
e.printStackTrace(); } } catch (NoSuchMethodException e) {
e.printStackTrace(); } catch (SecurityException e) {
e.printStackTrace(); } }}

结果如下:

在这里插入图片描述

转载地址:https://it9527.blog.csdn.net/article/details/110940777 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Java框架技术核心基石系列教程(05)——利用Class全面解析类信息(1)
下一篇:Java框架技术核心基石系列教程(04)——Class类详解

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2024年04月09日 18时20分00秒