单例模式

来源:互联网 发布:网络教育档案存放 编辑:程序博客网 时间:2024/06/07 05:04
/**
 *
 * @author ALbert
 * @category 单例模式
 *
 */
/**
 * 单例模式:能确保一个类只有一个实例,自行提供这个实例,并向整个系统提供这个实例;
 * 特点:1.一个类只能有一个实例,
 *   2.自己创建这个实例,
 *   3.整个系统都要使用这个实例;
 * 优点:1.可以避免实例重复创建,
 *   2.可以避免存在多个实例,引起的程序逻辑错误,
 *   3.节约内存。
 */
 /**
  *
  * @author 苏雨航
  *@category 饿汉式
  */
 class Single{
  private static Single single=new Single();
  private String name;
  public static Single getSingle(){
   return single;
  }
  private Single(){
   
  }
  
 }
 
 /**
  *
  * @author 苏雨航
  *@category 懒汉式
  */
 class Singleton{
  private static Singleton singleton=null;
  private Singleton(){
   
  }
  public static Singleton getSingleton(){
   if(singleton!=null){
    singleton=new Singleton();
   }
   return singleton;
  } 
  
 }
 /**
  *
  * @author 苏雨航
  *@category 测试类
  */
public class Test{
 public static void main(String[] args) {
  Single s1=Single.getSingle();
  Single s2=Single.getSingle();
  if(s1==s2){
   System.out.println("s1==s2");
  }
  
  Singleton sl1=Singleton.getSingleton();
  Singleton sl2=Singleton.getSingleton();
  if(sl1==sl2){
   System.out.println("sl1和sl2是同一个实例");
  }
 }
 
0 0
原创粉丝点击