php、java实现单例模式

来源:互联网 发布:21天学通c语言百度云 编辑:程序博客网 时间:2024/04/29 11:25

一、java实现的三种方式

方式一

public class SingleInstance {    private static final SingleInstance instance = new SingleInstance();    private SingleInstance(){}    public SingleInstance getInstance(){        return instance;    }}

方式二

public class SingleInstance {    private SingleInstance(){}    public SingleInstance getInstance(){        return SingleInstanceFactory.instance;    }    private static class SingleInstanceFactory{        private static final SingleInstance instance = new SingleInstance();     }}

方式三

public class SingleInstance {    private static SingleInstance instance = null;    private SingleInstance(){}    public static SingleInstance getInstance(){        if(instance == null){            synchronized (SingleInstance.class){                if(instance == null){                    instance = new SingleInstance();                }            }        }        return instance;    }}

二、php方式

class SingleInstance{      private function __construct(){          echo "11111";      }      public static function getInstance()      {          static $instance;          if(false == $instance)          {              $instance = new self();          }          return $instance;      } }
0 0
原创粉丝点击