---------------------- <a href="http://www.itheima.com"target="blank">ASP.Net+Unity开发</a>、<a href="http://www.itheima.com"target="blank">.Net培训</a>、期待与您交流! ----------------------
单例模式:
特点:1、单例类只能有一个实例
2、单例类必须自己创建自己的唯一实例
3、单例类必须给所有其他对象提供这一实例
好处:1、节省系统开销
2、保存该实例的状态
分类:
懒汉式
核心代码:
public class LazySingleton {
public static LazySingleton lazySingleton = null;
private LazySingleton() {
}
synchronized public static LazySingleton getInstance() {
if (lazySingleton == null) {
lazySingleton = new LazySingleton();
}
return lazySingleton;
}
}
饿汉式
核心代码
public class HungerSingleton {
private static final HungerSingleton HUNGERSINGLETON = new HungerSingleton();
private HungerSingleton() {
}
public HungerSingleton getInstance() {
return HUNGERSINGLETON;
}
}
推荐使用饿汉式
因为在懒汉式中,由于存在多线程访问时,懒汉式可能会出现创建出多个实例,而若对其使用synchronized的话,则又会降低程序性能,所以推荐使用饿汉式。
登记式
import java.util.HashMap;
import java.util.Map;
public class RegistrationSingleton {
public static Map<String, RegistrationSingleton> map = new HashMap<String, RegistrationSingleton>();
static {
RegistrationSingleton rs = new RegistrationSingleton();
map.put(rs.getClass().getName(), rs);
}
protected RegistrationSingleton()// 此处为public或者protected都可,因为外界都无法访问
{
}
public static RegistrationSingleton getInstance(String name) {
if (name == null) {
name = "RegistrationSingleton";
}
if (map.get(name) == null) {
try {
map.put(name, (RegistrationSingleton) Class.forName(name)
.newInstance());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return map.get(name);
}
}
如果有个学生类不是单例,但是我们想要把他当成单例模式,就是也只能创建出一个学生实例,我们就可以用到这个,
Student s1=RegistrationSingleton.getInstance(“Student”);//注意此处Student必须为完整包名。注意学习这种思想,当然public static RegistrationSingleton getInstance(String name) 此时RegistrationSingleton必须写成Object,里面好多东西也需要改改。
修改如下:
import java.util.HashMap;
import java.util.Map;
public class RegistrationSingleton {
public static Map<String, Object> map = new HashMap<String, Object>();
static {
RegistrationSingleton rs = new RegistrationSingleton();
map.put(rs.getClass().getName(), rs);
}
protected RegistrationSingleton()// 此处为public或者protected都可,因为外界都无法访问
{
}
public static Object getInstance(String name) {
if (map.get(name) == null) {
try {
map.put(name, Class.forName(name).newInstance());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return map.get(name);
}
}
---------------------
<a href="http://www.itheima.com"target="blank">ASP.Net+Unity开发</a>、<a href="http://www.itheima.com"target="blank">.Net培训</a>、期待与您交流! ----------------------