What is the use of making constructor private in a

2019-01-02 19:29发布

Why should we make the constructor private in class? As we always need the constructor to be public.

标签: oop
23条回答
梦醉为红颜
2楼-- · 2019-01-02 19:56

I saw a question from you addressing the same issue.

Simply if you don't want to allow the others to create instances, then keep the constuctor within a limited scope. The practical application (An example) is the singleton pattern.

查看更多
萌妹纸的霸气范
4楼-- · 2019-01-02 20:00

You shouldn't make the constructor private. Period. Make it protected, so you can extend the class if you need to.

Edit: I'm standing by that, no matter how many downvotes you throw at this. You're cutting off the potential for future development on the code. If other users or programmers are really determined to extend the class, then they'll just change the constructor to protected in source or bytecode. You will have accomplished nothing besides to make their life a little harder. Include a warning in your constructor's comments, and leave it at that.

If it's a utility class, the simpler, more correct, and more elegant solution is to mark the whole class "static final" to prevent extension. It doesn't do any good to just mark the constructor private; a really determined user may always use reflection to obtain the constructor.

Valid uses:

  • One good use of a protected constructor is to force use of static factory methods, which allow you to limit instantiation or pool & reuse expensive resources (DB connections, native resources).
  • Singletons (usually not good practice, but sometimes necessary)
查看更多
情到深处是孤独
5楼-- · 2019-01-02 20:02

We can also have private constructor, to enfore the object's creation by a specific class only(For security reasons).

One way to do it is through having a friend class.

C++ example:

class ClientClass;
class SecureClass 
{
  private:
    SecureClass();   // Constructor is private.
    friend class ClientClass;  // All methods in 
                               //ClientClass have access to private
                               // &   protected methods of SecureClass.
};

class ClientClass
{
public:
    ClientClass();
    SecureClass* CreateSecureClass()
     { 
           return (new SecureClass());  // we can access 
                                        // constructor of 
                                        // SecureClass as 
                                        // ClientClass is friend 
                                        // of SecureClass.
     }
};

Note: Note: Only ClientClass (since it is friend of SecureClass) can call SecureClass's Constructor.

查看更多
后来的你喜欢了谁
6楼-- · 2019-01-02 20:04

On use of private constructors could also be to increase readability/maintainability in the face of domain-driven design. From "Microsoft .NET - Architecing Applications for the Enterprise, 2nd Edition":

var request = new OrderRequest(1234);

Quote, "There are two problems here. First, when looking at the code, one can hardly guess what’s going on. An instance of OrderRequest is being created, but why and using which data? What’s 1234? This leads to the second problem: you are violating the ubiquitous language of the bounded context. The language probably says something like this: a customer can issue an order request and is allowed to specify a purchase ID. If that’s the case, here’s a better way to get a new OrderRequest instance:"

var request = OrderRequest.CreateForCustomer(1234);

where

private OrderRequest() { ... }

public OrderRequest CreateForCustomer (int customerId)
{
    var request = new OrderRequest();
    ...
    return request;
}

I'm not advocating this for every single class, but for the above DDD scenario I think it makes perfect sense to prevent a direct creation of a new object.

查看更多
余生无你
7楼-- · 2019-01-02 20:06

Everyone is stuck on the Singleton thing, wow.

Other things:

  • Stop people from creating your class on the stack; make private constructors and only hand back pointers via a factory method.
  • Preventing creating copys of the class (private copy constructor)
查看更多
登录 后发表回答