package com.secondDay.register;
import java.util.HashMap;
public class RegSingleton {
private static HashMap map = new HashMap();
static {
RegSingleton x=new RegSingleton();
map.put(x.getClass().getName(),x);
}
protected RegSingleton() {
}
public static RegSingleton getInstance(String name) throws Exception {
if (name == null){
name=RegSingleton.class.getName();
}
if (map.get(name) == null) {
try{
map.put(name,Class.forName(name).newInstance());
}catch (Exception e) {
System.out.println("Error happen\n"+e.getMessage());
}
}
return (RegSingleton) map.get(name);
}
public void about(){
System.out.println("parent");
}
}
package com.secondDay.register;
public class RegChildSingleton extends RegSingleton{
protected RegChildSingleton(){
}
public static RegChildSingleton getInstance() throws Exception {
//继承,调用父类的方法
return (RegChildSingleton) RegSingleton.getInstance(RegChildSingleton.class.getName());
}
public void about(){
System.out.println("child");
}
}
package com.secondDay.register;
public class RegSingletonTest {
public static void main(String[] args) throws Exception {
RegSingleton.getInstance(null).about();
RegChildSingleton.getInstance().about();
}
}
登记式单例
最新推荐文章于 2024-06-09 18:24:15 发布