将类的构造函数声明为private,只能在类内通过new Test()创建对象,在类内实现getInstance() 函数,实现new Test()创建对象。
下面为实现代码:
/**
* @Description:Java实现单例
* @author: 诗人的情人
* @Date: 8:56 上午 2019/10/20
*/
public class JustForTest {
public static void main(String[] args) {
Test.getInstance().fun();
Test.getInstance().fun();
}
}
class Test{
private volatile static Test instance;
public static Test getInstance() {
if (instance == null) {
synchronized (Test.class) {
if (instance == null) {
instance = new Test();
}
}
}
return instance;
}
private Test() {
System.out.println("调用构造函数");
}
public static void fun() {
System.out.println("调用fun");
}
}
输出:
调用构造函数
调用fun
调用fun
Process finished with exit code 0
从输出结果可以看到:调用了两次fun()函数,构造函数只调用了一次。
代码很简单,记录一下自己的成长过程吧。