Why is it mandatory to have private Constructor in

2020-02-05 09:58发布

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;

        }
    }

10条回答
一夜七次
2楼-- · 2020-02-05 10:37

It is mandatory. Your code may be fine, but others can use this code and instantiate another object, or you might do it by accident. This way is safe.

查看更多
\"骚年 ilove
3楼-- · 2020-02-05 10:40

For the singleton pattern you use an private constructor to ensure that no other instances can be created, otherwise it wouldn't be a singleton.

查看更多
孤傲高冷的网名
4楼-- · 2020-02-05 10:43

A static class is different from a singleton in that a a singleton class enforces that there is always at most one instance. A static class has no instances, and is just a bundle of static functions and static data.

So for a Singleton class, i.e. one with at most one instance, then a private constructor is required.

In your example, it looks like the Singleton class fits more than the static class- because of the connection and dataSource members. Make those members private, your constructor private and provide static methods that reference a static ConnPoolFactory instance. If instance is null, create a new one, otherwise just use it.

查看更多
Fickle 薄情
5楼-- · 2020-02-05 10:44

The comment as you said that If I am complete owner of my application and I will never commit mistake of creating instance of singleton class directly using the public constructor but will use the static method for getting it. But in real world, often application switch hands between multiple developers. If the new developer is not aware that you want only one instance of the class in the application, he/she may accidently create another one by using the public constructor.

查看更多
一夜七次
6楼-- · 2020-02-05 10:48

The Singleton pattern typically includes a non-public constructor, for two reasons. A constructor has to exist because if there's no constructor at all, a public default constructor is included. If you have a public constructor, though, people can just make their own singletons at will (which someone inevitably will, meaning there can be more than one).

It doesn't have to be private, though. In fact, as i heard it, the Singleton pattern as specified by the GoF mentions a protected constructor, for some odd reason. Something about inheritance, i hear, but singletons and inheritance do not play well together at all anyway.

It's even possible to have a public constructor, as long as it can detect whether an instance already exists and throw an exception or something if it does. That'd be enough to guarantee singleness. But it's rather uncommon, because doing it that way complicates things by providing two apparent ways to acquire an instance -- only one of which will actually work. If you don't want outside code to be able to create a second instance, why should a constructor be part of the public interface?

查看更多
够拽才男人
7楼-- · 2020-02-05 10:50

If you don't need lazy initiation:

public class Singleton {
    private static final Singleton instance = new Singleton();

    // Private constructor prevents instantiation from other classes
    private Singleton() { }

    public static Singleton getInstance() {
            return instance;
    }
}

is the best way, because is thread safe.

查看更多
登录 后发表回答