与其尝试通过更新状态来解决这个问题,不如尝试以函数式编程的方式解决它。例如,在给定已知条件(例如生产开始时)的情况下,编写一个可以计算资源量的函数。非常简化:
基于状态的模型:
class Gold {
public $amount = 0;
}
class GoldDigger {
public $amount_per_second = 1;
}
$player_gold = new Gold();
$player_worker = new GoldDigger();
while (true) {
$player_gold->amount += $player_worker->amount_per_second;
sleep(1);
echo "Player has {$player_gold->amount} gold pieces\n";
}
基于功能的模型:
class Gold {
public $workers = array();
function getAmount() {
$total = 0;
foreach ($this->workers as $worker) {
$total += $worker->getAmount();
}
return $total;
}
}
class GoldDigger {
public $amount_per_second = 1;
public $started = 0;
function __construct() {
$this->started = time();
}
function getAmount() {
return $this->amount_per_second * (time() - $this->started);
}
}
$player_gold = new Gold();
$player_gold->workers[] = new GoldDigger();
while (true) {
sleep(1);
echo "Player has {$player_gold->getAmount()} gold pieces\n";
}
这两个例子都有点做作——您可能会将数据存储在数据库或类似数据库中,这会使事情变得有些复杂,但我希望它能够说明两种策略之间的区别。