php与设计模式-备忘录模式

备忘录模式

又叫做快照模式或Token模式,在不破坏封闭的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。

Demo

liveLevel,$this->attackLevel,$this->defenseLevel)); 
       } 

       //恢复状态 
       public function RecoveryState(RoleStateMemento $_memento) 
       { 
           $this->liveLevel = $_memento->liveLevel; 
           $this->attackLevel = $_memento->attackLevel; 
           $this->defenseLevel = $_memento->defenseLevel; 
       } 

       //------------其他属性及操作-------------- 
       //获得初始状态 
       public function GetInitState() 
       { 
           $this->defenseLevel = 100; 
           $this->attackLevel = 100; 
           $this->liveLevel = 100; 
       } 

       //状态显示 
       public function StateDisplay() 
       { 
           echo "角色状态:
"; echo "生命力:{$this->liveLevel}
"; echo "攻击力:{$this->attackLevel}
"; echo "防御力:{$this->defenseLevel}
"; } //被攻击 public function BeenAttack() { $this->liveLevel -= 9.5; if($this->liveLevel<=0) { $this->liveLevel = 0; echo "呃,该角色阵亡了!
"; echo "Game Over!
"; return; } $this->attackLevel -= 1.1; if($this->attackLevel<=0) { $this->attackLevel = 0; } $this->defenseLevel -= 0.5; if($this->defenseLevel<=0) { $this->defenseLevel = 0; } } } //角色状态存储箱类 class RoleStateMemento { public $liveLevel; public $attackLevel; public $defenseLevel; public function RoleStateMemento($_ll,$_al,$_dl) { $this->liveLevel=$_ll; $this->attackLevel=$_al; $this->defenseLevel=$_dl; } } //游戏角色状态管理者类 class RoleStateManager { public $memento; } //开战前 $ufo = new GameRole(); $ufo->GetInitState(); echo "----------------开战前-----------------
"; $ufo->StateDisplay(); //保存进度 $roleMan = new RoleStateManager(); $roleMan->memento = $ufo->SaveState(); echo "----------------战斗中-----------------
"; $num=1; //大战Boss5个回合 for ($i = 0; $i <13;$i++ ) { echo "-------------第{$num}回合-------------
"; $ufo->BeenAttack(); $ufo->StateDisplay(); $num++; //角色阵亡 if($ufo->liveLevel<=0) { break; } } echo "----------------恢复状态-----------------
"; //恢复之前状态 $ufo->RecoveryState($roleMan->memento); $ufo->StateDisplay();

请关注我的订阅号

订阅号.png

你可能感兴趣的:(php与设计模式-备忘录模式)