php備忘模式之星際爭霸

來源:互聯網
上載者:User

我們在玩星際任務版或者單機與電腦對戰的時候,有時候會突然要離開遊戲,或者在出兵前面,需要儲存一下遊戲。

那麼我們通過什麼辦法來儲存目前的資訊呢?而且在任何時候,可以恢複儲存的遊戲呢?

待解決的問題:儲存遊戲的一切資訊,如果恢複的時候完全還原。

思路:建立一個專門儲存資訊的類,讓他來處理這些事情,就像一本備忘錄。
為了簡單,我們這裡用恢複一個玩家的資訊來示範。

 代碼如下 複製代碼

//備忘類

class Memento

{

  //水晶礦

  public $ore;

  //氣礦

  public $gas;

  //玩家所有的部隊對象

  public $troop;

  //玩家所有的建築對象

  public $building;

  //構造方法,參數為要儲存的玩家的對象,這裡強制參數的類型為Player類

  public function __construct(Player $player)

  {

  //儲存這個玩家的水晶礦

  $this->ore = $player->ore;

  //儲存這個玩家的氣礦

  $this->gas = $player->gas;

  //儲存這個玩家所有的部隊對象

  $this->troop = $player->troop;

  //儲存這個玩家所有的建築對象

  $this->building = $player->building;

  }

}

//玩家的類

class Player

{

  //水晶礦

  public $ore;

  //氣礦

  public $gas;

  //玩家所有的部隊對象

  public $troop;

  //玩家所有的建築對象

  public $building;

  //擷取這個玩家的備忘對象

  public function getMemento()

  {

   return new Memento($this);

  }

  //用這個玩家的備忘對象來恢複這個玩家,這裡強制參數的類型為Memento類

  public function restore(Memento $m)

  {

    //水晶礦

  $this->ore = $m->ore;

  //氣礦

  $this->gas = $m->gas;

  //玩家所有的部隊對象

  $this->troop = $m->troop;

  //玩家所有的建築對象

  $this->building = $m->building;

  }

}

//製造一個玩家

$p1 = new Player();

//假設他現在采了100水晶礦

$p1->ore = 100;

//我們先儲存遊戲,然後繼續玩遊戲

$m = $p1->getMemento();

//假設他現在采了200水晶礦

$p1->ore = 200;

//我們現在載入原來儲存的遊戲

$p1->restore($m);

//輸出水晶礦,可以看到已經變成原來儲存的狀態了

echo $p1->ore;

用途總結:備忘模式使得我們可以儲存某一時刻為止的資訊,然後在需要的時候,將需要的資訊恢複,就像遊戲的儲存和載入歸檔一樣。

實現總結:需要一個備忘類來儲存資訊,被儲存的類需要實現產生備忘對象的方法,以及調用備忘對象來恢複自己狀態的方法。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.