美文网首页
Java单例模式

Java单例模式

作者: 风雪_夜归人 | 来源:发表于2020-02-06 22:51 被阅读0次

    单例模式:一个类只会生成唯一的一个对象

    • 代码一 :

    public class SingpatternTest
    {
      public static void main(String[] args)
      {
          Singpattern singpattern1 = singpattern.getInstance();
          Singpattern singpattern2 = singpattern.getInstance();
          system.out.println(singpattern1  == singpattern2);
      }
    
    }
    
    class Singpattern
    {
    
      private  static Singpattern singpattern = new Singpattern();
    
      private Singpattern()
      {
    
      }
    
      public  static Singpattern getInstance()
      {
        return new Singleton();
      }
    
    }
    
    • 代码二 :

    public class SingpatternTest
    {
      public static void main(String[] args)
      {
          Singpattern singpattern1 = singpattern.getInstance();
          Singpattern singpattern2 = singpattern.getInstance();
          system.out.println(singpattern1  == singpattern2);
      }
    
    }
    class Singpattern
    {
      private  static Singpattern singpattern;
    
      private Singpattern()
      {
    
      }
    
      public  static Singpattern getInstance()
      {
        if(singpattern = null)
        {
           singpattern = new Singpattern();
         }
    
        return new Singleton();
      }
    
    }
    

    相关文章

      网友评论

          本文标题:Java单例模式

          本文链接:https://www.haomeiwen.com/subject/wfrpxhtx.html