我仍然可以通过使用构造函数实例化,虽然在类定义中它已被声明为私有构造函数??? 这是代码片段:
public class Singleton {
private static Singleton instance;
private String name;
/* Private constructor prevents other classes from instantiating */
private Singleton(String name) {
this.name = name;
// Optional code
}
/*
* Static factory method that creates instance instead of constructor.
* Synchronization helps to block any attempt to instantiate from simultaneous
* thread hence break concept of singleton.
* This method uses a technique known as lazy instantiation.
*/
public static synchronized Singleton getInstance(String name) {
if (instance == null) {
instance = new Singleton(name);
}
return instance;
}
/* Override Object clone method to avoid cloning */
@Override
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
public String getName() {
return name;
}
/* Example of using singleton object */
public static void main(String[] args) {
Singleton a = new Singleton("Hoang");
Singleton b = new Singleton("Shiha");
System.out.println(a.getName());
System.out.println(b.getName());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
383 次 |
| 最近记录: |