design-patterns-for-humans
design-patterns-for-humans copied to clipboard
Didn't see any implementation difference between state and strategy pattern
Ideally, only state pattern should store the state. Strategy pattern should pass strategy as an argument to the method.
The best example of state pattern is something determined. The feature of the pattern is branching without if
.
interface PhoneState {
public function pickUp(): PhoneState;
public function hangUp(): PhoneState;
public function dial(): PhoneState;
}
// states implementation
class PhoneStateIdle implements PhoneState {
public function pickUp(): PhoneState {
return new PhoneStatePickedUp();
}
public function hangUp(): PhoneState {
throw new Exception("already idle");
}
public function dial(): PhoneState {
throw new Exception("unable to dial in idle state");
}
}
class PhoneStatePickedUp implements PhoneState {
public function pickUp(): PhoneState {
throw new Exception("already picked up");
}
public function hangUp(): PhoneState {
return new PhoneStateIdle();
}
public function dial(): PhoneState {
return new PhoneStateCalling();
}
}
class PhoneStateCalling implements PhoneState {
public function pickUp(): PhoneState {
throw new Exception("already picked up");
}
public function hangUp(): PhoneState {
return new PhoneStateIdle();
}
public function dial(): PhoneState {
throw new Exception("already dialing");
}
}
// an automate
class Phone {
private $state;
public function __construct() {
$this->state = new PhoneStateIdle();
}
public function pickUp() {
$this->state = $this->state->pickUp();
}
public function hangUp() {
$this->state = $this->state->hangUp();
}
public function dial() {
$this->state = $this->state->dial();
}
}
@dlnsk you should open a PR with this example :)
Wow, thank you
Both of the examples have been updated. Thank you!