標籤:des http java 使用 os io 資料 問題
之前對java的設計模式略有瞭解,但是螃蟹目前是靠PHP吃飯,所以對於進階學習php設計模式還是很有必要。螃蟹雖然做開發兩年了,但是在老鳥眼中還是菜鳥,為了自己寫的代碼更容易維護和進行團隊協作,所以我要搞定設計模式。希望螃蟹今年能創業成功或找個好工作。
1.適配器模式
螃蟹的理解是你買了港行的iphone手機,發現自家的插座和手機內建的插頭不配,怎麼辦呢,就需要一個轉換器(適配器)。可能原來系統的類不是你設計的,但是現在你要使用原來的類,發現有問題,但原來的類又不能動,或者不需要動,這樣你寫一個類繼承原來的類,再在新的類中添加想要的東西,再拿去用就可以了。螃蟹還是寫一下代碼記得牢固一點。
參考項目模組:會員系統
螃蟹之前遇到過某項目的會員系統,原來的會員對象已經定義了,但是新的項目又需要使用原系統的對象,但是新項目又增加了幾個屬性,這樣適配器模式就利用上了,下面代碼敲一遍,螃蟹寫的代碼都是在zend studio裡面手打的並且測試過了的
原會員系統會員對象類User.class.php:
<?php class User{private $username = null;private $password = null;function __construct($user){$this->username = $user[‘username‘];$this->password = $user[‘password‘];}/** * @return the $username */public function getUsername() {return $this->username;}/** * @return the $password */public function getPassword() {return $this->password;}/** * @param NULL $username */public function setUsername($username) {$this->username = $username;}/** * @param NULL $password */public function setPassword($password) {$this->password = $password;}}?>
現在需要增加郵箱和簡歷,那原來的類不能直接改,那就使用適配器吧,建立UserAdapter.class.php
<?php require(‘User.class.php‘);class UserAdapter extends User{private $email = null;private $description = null;function __construct($user){parent::__construct($user);$this->email = $user[‘email‘];$this->description = $user[‘description‘];}/** * @return the $email */public function getEmail() {return $this->email;}/** * @return the $description */public function getDescription() {return $this->description;}/** * @param NULL $email */public function setEmail($email) {$this->email = $email;}/** * @param NULL $description */public function setDescription($description) {$this->description = $description;}}?>
好的,我來測試一下結果:TestAdapter.php
<?php require(‘UserAdapter.class.php‘);//類比使用者資料$user = array(‘username‘=>‘螃蟹‘,‘password‘=>‘SB123456‘,‘email‘=>‘[email protected]‘,‘description‘=>‘螃蟹也會思考‘);//執行個體化配接器物件$userobj = new UserAdapter($user);//輸出結果echo ‘ Username: ‘.$userobj->getUsername();echo ‘<br>Password: ‘.$userobj->getPassword();echo ‘<br>Email: ‘.$userobj->getEmail();echo ‘<br>Description: ‘.$userobj->getDescription();//改變密碼和Email$userobj->setPassword(‘ok456789‘);$userobj->setEmail(‘[email protected]‘);//輸出改變後的結果echo ‘<br><br>Password: ‘.$userobj->getPassword();echo ‘<br>Email: ‘.$userobj->getEmail();?>
測試結果:
Username: 螃蟹Password: SB123456Email: [email protected]Description: 螃蟹也會思考Password: ok456789Email: [email protected]
螃蟹覺得看起來高深的設計模式也還好懂,今天就到這裡了,明天再學習新的設計模式了,繼續單身的橫著睡了。