Preventing class instantiation from other classes

后端 未结 2 1956
青春惊慌失措
青春惊慌失措 2021-01-23 03:49

I\'m working with a domain, view and controllers. Each containing their own classes.

The domain contains a lot of classes that should not be instantiated in classes outs

2条回答
  •  梦谈多话
    2021-01-23 04:21

    If you want to control the instantiation of a class from outside of the class then you may create it's constructor private like -

    class A{
    
       private A(){
          // do some thing
       } 
    
       public static getInstance(){
    
       }
    }   
    

    Now now instance of class A can be created form the outside of the class. But if the outer world realy need an instance of the class then they can use the static method getInstance(). This construction prevents the outer world to create an instance of the class using new keyword.

    Hope it will Help.
    Thanks.

提交回复
热议问题