design-patterns-for-humans icon indicating copy to clipboard operation
design-patterns-for-humans copied to clipboard

Didn't see any implementation difference between state and strategy pattern

Open ajay109458 opened this issue 6 years ago • 3 comments

Ideally, only state pattern should store the state. Strategy pattern should pass strategy as an argument to the method.

ajay109458 avatar Oct 12 '18 09:10 ajay109458

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 avatar Jan 16 '19 07:01 dlnsk

@dlnsk you should open a PR with this example :)

MathMesquita avatar Feb 08 '19 13:02 MathMesquita

Wow, thank you

CaetanoBorges avatar Apr 18 '22 19:04 CaetanoBorges

Both of the examples have been updated. Thank you!

kamranahmedse avatar Apr 27 '23 11:04 kamranahmedse