2013-12-19 61 views
-3

具體而言,我有一個二級請求和utils的,啓動一類全球

class Request 
{ 
public function __construct() 
{ 
//constructor method 
} 
public function request() 
{ 
    $utils=new Utils; 
    $consolidated_errors=$utils->array_remove_empty($all_params_error); 
} 
public function process() 
{ 
    $utils=new Utils; 
    $consolidated_errors=$utils->another_method($all_params_error); 
}                 
} 

和類utils的,

class Utils 
{ 
public function __construct() 
{ 
//constructor method 
} 
public function array_remove_empty() 
{ 
    //returns a variable. 
    }   
public function another_method() 
{ 
    //returns a variable. 
}  

} 

,你可以看到,我初始化類兩次在請求類,我的問題是,以任何方式初始化全球範圍內的類和使用整個類?

+2

你已經發布的代碼是一個PHP代碼,爲​​什麼你的java下的標籤呢? – dreamweiver

回答

1

您正在尋找Singleton模式

以下證明你的類

public class Utils { 
    private static Utils uniqInstance; 

    private Utils() { 
    } 

    public static synchronized Utils getInstance() { 
    if (uniqInstance == null) { 
     uniqInstance = new Utils(); 
    } 
    return uniqInstance; 
    } 
    // other useful methods here 
} 

非常基本的辛格爾頓例如使用靜態工廠模式

0

上面的代碼看起來並不像Java獲得實例對我來說,但無論如何,

你可以創建班級的班級private Utils myUtuils = new Utils();

或 有類作爲一個靜態類,然後就直接用它在你的方法

public function process() 
{ 
    consolidated_errors= Utils.another_method($all_params_error); 
}                 
}