为什么在单例类中必须有私有构造函数

编程入门 行业动态 更新时间:2024-10-26 14:37:42
本文介绍了为什么在单例类中必须有私有构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是我获取数据库连接的单例类.

This is my singleton class for obtaining the database connection.

我在这里有一个问题:为什么在单例类中必须有一个私有构造函数(因为在我的整个应用程序中,我只调用了一次这个类)并且因为一个类的一个实例可以使用静态方法来实现?

I have a question here: why it compulsory to have a private constructor inside a singleton class (as throughout my entire application I am calling this class only once) and as one instance of a class can be achieved using the static method?

这个私有构造函数可以避免吗,还是必须的?

Can this private constructor can be avoided, or is it mantadatory?

public class ConnPoolFactory { private static DataSource dataSource; private static Connection connection; private ConnPoolFactory() { System.out.println(" ConnPoolFactory cons is called "); } public static synchronized Connection getConnection() throws SQLException { try { if (connection == null) { Context initContext = new InitialContext(); Context envContext = (Context) initContext .lookup("java:/comp/env"); dataSource = (DataSource) envContext.lookup("jdbc/Naresh"); connection = dataSource.getConnection(); } else { return connection; } } catch (NamingException e) { e.printStackTrace(); } return connection; } }

推荐答案

否则每个人都可以创建你的类的一个实例,这样它就不再是一个单例了.根据定义,单例只能存在一个实例.

Otherwise everyone can create an instance of your class, so it's not a singleton any more. For a singleton by definition there can exist only one instance.

更多推荐

为什么在单例类中必须有私有构造函数

本文发布于:2023-10-31 05:45:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545186.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   类中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!