《Thinking in Java》——构造器是private时如何创建对象?

xiaoxiao2021-02-28  49

构造器是private时如何创建对象?

可以通过static成员进行创建,如:

class A { private A(){} //构造器是private修饰,不能在本类外通过new A();创建对象 public static A construct() { return new A(); //在public static修饰的方法中通过new A()创建对象, } }

或者:

class B { private B(){} //构造器是private修饰,不能在本类外通过new B();创建对象 private static B b = new B(); //创建private static修饰的对象b public static B construct() { return b; //在public static修饰的方法中返回对象b } }

通过A.construct()或者B.construct()便可创建对象。 其中第二种方法是设计模式中的单例模式,始终只能创建一个对象,并只能通过B.construct()访问到这个对象。

转载请注明原文地址: https://www.6miu.com/read-78938.html

最新回复(0)