Java 构造函数
Java中的私有构造函数和单例类
我们首先分析下面的问题:
我们可以有私人构造函数吗?
正如你可以很容易猜到的,就像我们可以为构造函数提供访问说明符一样。如果它是私人的,那么它只能在课堂内进行访问。
我们需要这样的“私有构造函数”吗?
我们可以使用私有构造函数的各种场景。主要的是
内部构造器链接
单件类设计模式
什么是Singleton类?
顾名思义,如果一个类将该类的对象数限制为一个,则该类称为单例。
对于这样的类,我们不能只有一个对象。
Singleton类广泛应用于网络和数据库连接等概念。
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
我们改变了ax的值,bx的值也得到了更新,因为'a'和'b'都指向同一个对象,即它们是单例类的对象。