《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.
创建一个单例类,只能够创建一个对象根据所给的类。
方法:
把类的构造方法设为私有的,这样就不能够继承了。
然后提供一个静态的方法,来获取对象的实例;
代码:
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(); } }
相关文章推荐
- 黑马程序员——JAVA常见错误整理
- 做一个有想法的程序员,做一个属于自己的神器
- 技术第一,还是?
- 【剑指Offer学习】【面试题31:连续子数组的最大和】
- 黑马程序员----OC学习笔记之category,extension,protocol
- 【剑指Offer学习】【面试题30:最小的k个数】
- 【剑指Offer学习】【面试题29 :数组中出现次数超过一半的数字】
- 黑马程序员----OC学习之小知识学习
- 《Java面试试题》找出前半部分数组和后半部分数组之和相同的索引
- 《Java面试试题》找出连续数组中相同的两个数值
- 摘录-IT企业必读的200个.NET面试题-06 .NET中的高级特性
- Java面试题,以下题目取自“Java面试宝典”
- 【Web探索之旅】第四部分:Web程序员
- 传统IT转互联网面试经验分享
- 黑马程序员----异常和异常的处理方式
- Android基础面试题
- 程序员天生就是查理·芒格
- [心得]传统IT转互联网面试经验分享
- 面试题
- 黑马程序员——2,零碎的JAVA基础