各位大侠好,小弟接触面向对象也有段时间了,可每次设计新系统时都会遇到关于对象如何拆分与设计的问题,特来请教一番。
比如,现在的系统要求有:用户,角色,积分。
用户有:用户名,密码。
角色有:角色名。
积分有:积分值,所属用户,所属模块。
通过阅读网上的帖子,我觉得:
用户对象应该包含:用户名,密码,角色对象,积分对象
code:
class user {
public $username;
public $password;
public $role;
public $score;
}
请问是这样设计的吗?可我总感觉哪地方不对,或许我觉得,角色对象和积分对象不作为用户对象的属性,当需要获取用户对象时,重新new一下角色对象,然后将用户对象传入,这样获取用户所对应的角色。这样设计合理吗?
回复讨论(解决方案) 如果将角色、积分作为用户属性,那以后如果增加了新的元素,我不是要修改代码了吗?那样的话,用户对象就会变得好庞大。
可是如果不作为属性的话,角色、积分又确实是用户所拥有的。
你第一设计方案,本身并无不妥。只是写死了
而你的第二方案就灵活多了
至于是将用户传入角色,还是将角色传入用户,就是设计模式的选取了
?分可以分到另一? class去做。
?分?只增?改?分,不用?理其他?料。例如
class score{ private $_ouser; public function __construct($ouser){ $this->_ouser = $ouser; } public function add(){ } public function update(){ }}
具?要看需求。
感谢两位的回复。我对面向对象的知识还是太欠缺了,正如版主所说,我正在看设计模式的文章,希望能加深我对面向对象的理解。
上班?聊借此?手?面向?象基?
username = $username; $this->password = $password; }}//角色?class role{ private $username; public $rolename; function __construct($username,$rolename){ $this->username = $username; $this->rolename = $rolename; } function getroleusername() { return $this->username; }}//?分?class score{ private $username; private $module; public $score; function __construct($username,$module,$score){ $this->username = $username; $this->module = $module; $this->score = $score; } function getscoreusername() { return $this->username; } function getscoremodule() { return $this->module; } }//用 ?承用?基?class user extends baseuser{ public $role; public $score; function __construct($username,$password,$rolename,$score){ parent::__construct($username, $password); $this->role = new role($username,$rolename); $this->score = new score($username,module,$score); }}$user = new user(user9527,123,xiaoming,100);echo username: .$user->username;echo
;echo password: .$user->password;echo
;echo rolename: .$user->role->rolename;echo
;echo score: .$user->score->score;echo
;/*username: user9527password: 123rolename: xiaomingscore: 100 *///code end