对于开发中的设计模式来说,单例是必不可少的一种模式,自己平常在项目中开始也总有些不知道怎么更好的去使用单例,今天简单总结一下,自己用的情况:
简单的经典单例模式:
思想:多次new 同一个实体类的对象,不使用单例的情况下,会出现内容混乱,实体类是同样的,只是每次调用时做的操作不一样,那么结果可能出现混乱。
public class XFGamePlatform {
//设计模式-单例模式
public static XFGamePlatform instance=null;
private XFGamePlatform(){
//类的私有属性,实现只有本类中可new 一个对象
}
public static XFGamePlatform getIntance(){
if(instance==null){
instance = new XFGamePlatform();
}
return instance;
}
}
而使用单例后,把构造器改为私有属性,这样可以避免在本类以外去进行实例化对象,而自己判断处理。
当然这个经典的模式在多线程中使用,存在BUG,多线程中同时调用getIntance时,如果第一次调用new出一个,在没有new结束时,第二个调用getIntance,同样会再次new出一个对象,那么这个时候会出现两个不同的XFGamePlatform对象,等于单例失效了。
项目开发中怎么去实现多线程中使用单例设计模式:
第一种:自己常用的,缺点:资源消耗大。使用情况,项目中调用一次或则调用次数很小的情况下;
public class XFGamePlatform {
//设计模式-单例模式
public static XFGamePlatform instance=null;
private XFGamePlatform(){
//类的私有属性,实现只有本类中可new 一个对象
}
public static synchronized XFGamePlatform getIntance(){
if(instance==null){
instance = new XFGamePlatform();
}
return instance;
}
}
在对象实例化类中加一个同步锁,这样只有第一次调用结束后第二次才去调用,避免了再次new 出一个对象,但是资源消耗大;
第二种:直接粗暴的方式;
public class XFGamePlatform {
//设计模式-单例模式
public static XFGamePlatform instance=new XFGamePlatform();
private XFGamePlatform(){
//类的私有属性,实现只有本类中可new 一个对象
}
public static XFGamePlatform getIntance(){
if(instance==null){
instance = new XFGamePlatform();
}
return instance;
}
}
这种方式可以使用,自己认为尽量不要使用,每次调用时都直接创建一个对象,都明白,对象很耗内存的,如果项目中正好这次都没有用到这个对象,而内存中存在了,对于程序来说不妥。
第三种:多一次判断,双重锁方式,用过次数不多,多线程优化很好的一个方式;
public class XFGamePlatform {
//设计模式-单例模式
public static XFGamePlatform instance=null;
private XFGamePlatform(){
//类的私有属性,实现只有本类中可new 一个对象
}
public static XFGamePlatform getIntance(){
if(instance==null){
synchronized (XFGamePlatform.class) {
if(instance==null){
instance = new XFGamePlatform();
}
}
}
return instance;
}
}
这样写单例自己感觉更好些,减少的资源的消耗,同步锁用了一次,后面对象存在不会再次创建;
当然像这种模式或者代码的一些优化,根据自己的项目需求,自己的代码风格,思想也不一样,尤其是对一些基本项目框架的搭建上;慢慢修炼,相信自己会更好,技术先横向再纵向。