Java中的私有构造函数和单例类

我们先来分析一下这个问题:

null

我们能有私人施工人员吗?

正如您很容易猜到的,和任何方法一样,我们可以为构造函数提供访问说明符。如果它是私有的,那么它只能在类内部访问。

我们需要这样的“私人建设者”吗?

我们可以在不同的场景中使用私有构造函数。主要的是

  1. 内部构造函数链接
  2. 单例类设计模式

什么是单身班?

顾名思义,如果一个类将该类的对象数限制为一个,则称该类为单例。

对于这样的类,我们只能有一个对象。

单例类广泛应用于网络和数据库连接等概念中。

单例类的设计模式:

singleton类的构造函数是私有的,因此必须有另一种方法来获取该类的实例。这个问题可以通过使用类成员实例和工厂方法来返回类成员来解决。

下面是一个java示例,说明了这一点:

// Java program to demonstrate implementation of Singleton
// pattern using private constructors.
import java.io.*;
class MySingleton
{
static MySingleton instance = null ;
public int x = 10 ;
// private constructor can't be accessed outside the class
private MySingleton() {  }
// Factory method to provide the users with instances
static public MySingleton getInstance()
{
if (instance == null )
instance = new MySingleton();
return instance;
}
}
// Driver Class
class Main
{
public static void main(String args[])
{
MySingleton a = MySingleton.getInstance();
MySingleton b = MySingleton.getInstance();
a.x = a.x + 10 ;
System.out.println( "Value of a.x = " + a.x);
System.out.println( "Value of b.x = " + b.x);
}
}


输出:

Value of a.x = 20
Value of b.x = 20

我们更改了a.x的值,b.x的值也得到了更新,因为“a”和“b”都引用同一个对象,即它们是单例类的对象。

本文由 阿什图什·库马尔·辛格 .如果你喜欢GeekSforgek,并且想贡献自己的力量,你也可以写一篇文章,并将文章邮寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享