单例模式:设计成允许某个类在生命周期中只有一个对象存在
两种实现方法:懒汉式,饿汉式
一、懒汉式
- public class SingletonModel {
- private static SingletonModel singletonModel=null;
- private SingletonModel(){}
- public static SingletonModel getSingletonModelInstance(){
- if(singletonModel==null){
- singletonModel=new SingletonModel();
- }
- return singletonModel;
- }
二、饿汉式
- private static SingletonModel singletonModel=new SingletonModel();
- private SingletonModel(){}
- public static SingletonModel getSingletonModelInstance(){
- if(singletonModel!=null){
- return singletonModel;
- }else{
- singletonModel= new SingletonModel();
- return singletonModel;
- }
- }