软件修真界流传着23中上乘仙绝,下面先介绍我们常用的一种,单例模式.
背景:创造一个对象和创造一个人一样,创造了人,人需要资源,造的多了,地球就不堪重负,那么对象也是这样,但是对象和人不同,我们可以改变他的模式,减少不必要的开销,提高性能,提高安全.
解决办法:使用单例模式,每次的访问,我们之创建一个对象,用这一个对象去访问,其实这里的一个并不是正真的一个,是更具实际情况顶出来的,不能说1000万访问,值用一个,这样是不够用,且不合理的,也不能设置1000万个对象,这也是极大地浪费.
代码:
class TestEntity {
private static TestEntity testEntity=null;
TestEntity(){}
public static synchronized TestEntity getTestEntity(){
if(testEntity==null){
testEntity=new TestEntity();
}
return testEntity;
}
}
上边这种是我们推荐使用的.首先,设置的是封装属性,就是说不是谁都可以访问的.其次,static的设置有力于静态方法getTestEntity()的调用.再则,用synchornized同步方法,保证线程安全.而且,这样的方法只需要初始化一次就可以.
这一种:
class TestEntity {
TestEntity(){}
private static TestEntity testEntity=new TestEntity();
public static TestEntity getTestEntity(){
return testEntity;
}
}
其实,在类装载的时候(class loader)的时候用的也是单例.总结就是省内存,有利于垃圾回收,和线程安全.