日期:2014-05-16 浏览次数:20553 次
在java和php中都会用到很多的单例模式,那么它们有什么区别呢?昨天晚上我相互对比了一下,就做了个小小的总结,然后写了个很小的java单例和php单例
一、java 单例
//完成对用户登录的简单验证操作
class User{
private String name=null;//用户名
private String passwd=null;//密码
private static User ins = new User("这里可以传入常量,如“chunge”,此时构造函数要有对应形参。但是不支持在静态初始化函数中对它进行外部传递赋值");//单例实例对象
//初始化用户名密码的代码块
{
this.name="chunge";
this.passwd="111111";
}
//私有构造函数
private User(String n){
this.name=n;
}
//获取单例对象
public static User getIns(){
return ins;
}
//判断用户信息是否正确
public void checkUserInfo(String name , String passwd ){
if(name==this.name && passwd==this.passwd){
System.out.println("欢迎您" + this.name);
System.exit(1);
}
//用户密码不匹配
System.out.println("非法登录");
System.exit(1);
}
};
public class oop{
public static void main(String args[]){
User U = User.getIns();//实例化对象
U.checkUserInfo("chunge","111111");
}
};
<?php
/**网站全局配置类**/
class Config{
private static $ins="";
private $config_file="";//配置文件
public $WEB_CONFIG=array();
//关闭初始化函数
private function __construct(){
//引入全局配置文件
require_once ROOT."config/global_config.php";
$this->config_file=ROOT."config/global_config.php";
//赋值
$this->WEB_CONFIG=$WEB_CONFIG;
}
//禁用克隆函数
private function __clone(){
return false;
}
//单例模式
public static function getIns(){
if(!(self::$ins instanceof self)){
//如果不存在
self::$ins=new self();
}
return self::$ins;
}
////动态输出配置信息
public function configGet($key){
if(array_key_exists($key,$this->WEB_CONFIG)){
return $this->WEB_CONFIG[$key];
}else{
echo "该配置信息不存在";
}
}
//动态添加配置信息传入键即可
public function configSet($key,$value){
//真正存入
$str=file_get_contents($this->config_file);
//var_dump($str);
$tmp=$this->configGet($key);
$str=str_replace($tmp,$value,$str);
file_put_contents($this->config_file,$str);
//file_put_contents("ROOT1.php",$str);
}
////动态输出配置信息
public function __get($key){
if(array_key_exists($key,$this->WEB_CONFIG)){
return $this->WEB_CONFIG[$key];
}else{
echo "该配置信息不存在";
}
}
//动态添加配置信息
public function __set($key,$value){
//只是暂时的配置,未真正存入
$this->WEB_CONFIG[$key]=$value;
}
}
?>/**
笔记:类名字User 单例变量ins
在java和php中,单例模式的区别
1.类可以进行单例模式,和php一样
2.java的单例模式变量声明:
private/public static 类名字 对象名字 = new 类名字();
例如:private static User ins = new User();//已经进行了new操作
php的单例模式变量声明:
public/private static 对象名字=null;//只是声明,未进行new操作
例如:public static $ins = null;
3.java获得该单例对象方法
public static 类名字 方法名字(){
return 刚刚定义的对象名字
}
例如:
public static User getIns(){
return ins;//注意这里无法用this.但在php中,可以用self::获取
}
php中获取该单例对象方法
public function getIns(){
if(self::$ins==null || (!self::$ins instanceof self)){
self::$ins=new self();
}
return self::$ins;
}
4.在java中,单例模式如果初始化类中某些变量,因为其getIns()方法是静态的,如果变量不为静态的,则无法实例化该变量。即使构造函数需要传参,个人觉得可以直接用代码块 进行初始值的设置
在php中,单例模式可以对起进行初始值的赋值,如
public function getIns($can1,$can2.......){
if(self::$ins==null || (!self::$ins instanceof self)){
self::$ins=new self($can1,$can2........);//.......代表不限个数
}
return self::$ins;