您的位置:首页 > 职场人生

《Java面试试题》创建Singleton class单例类

2015-07-03 09:14 441 查看
描述:

Write a Singleton class

Singleton class means you can create only one object for the given class.

You can create a singleton class by making its constructor as private

so that you can restrict the creation of the object.

Provide a static method to get instance of the object

wherein you can handle the object creation inside the class only.

创建一个单例类,只能够创建一个对象根据所给的类。

方法:

把类的构造方法设为私有的,这样就不能够继承了。

然后提供一个静态的方法,来获取对象的实例;

代码:

package test;

public class MySingleton {
    private static MySingleton myObj;

    static{
        myObj = new MySingleton();
    }

    private MySingleton(){

    }

    public static MySingleton getInstance(){
        return myObj;
    }

    public void testMe(){
        System.out.print("It works");
    }

    public static void main(String[] args) {
        MySingleton msMySingleton = getInstance();
        msMySingleton.testMe();
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: