Java中的私有构造函数和Singleton类

2021年3月17日17:01:55 发表评论 611 次浏览

让我们首先分析以下问题:

我们可以有私有构造函数吗?

你很容易猜到, 就像任何方法一样, 我们可以为构造函数提供访问说明符。如果将其设为私有, 则只能在班级内部进行访问。

我们需要这样的"私有构造函数"吗?

在多种情况下, 我们可以使用私有构造函数。主要的是

  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"都指向同一对象, 即它们是单例类的对象。

本文作者:阿舒托什·库玛·辛格(Ashutosh Kumar Singh)。如果你喜欢lsbin并希望做出贡献, 那么你也可以写一篇文章并将你的文章邮寄到contribution@lsbin.org。查看你的文章出现在lsbin主页上, 并帮助其他Geeks。

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

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: