I recently just started learning design patterns using java and I was a bit confused and wondering how does state design pattern satisfy the open closed design principle as I couldn't online resource that has a concrete explanation on this..
CodePudding user response:
I reallt like this book Head First Design Patterns. It has a lot of examples with super simple explanations!
Imagine you have a game where hero can be any person in the world. Let's call him as Hero
.
He can run, swim and fly. You have a button where you can change its state or shape.
The code of Hero
would look like this:
public class Hero
{
IState _state;
public Hero()
{
_state = new SpiderManState();
}
public void Run()
{
_state.Run();
}
public void Swim()
{
_state.Swim();
}
public void Fly()
{
_state.Fly();
}
public void ChangeShape()
{
_state = _state.ChangeChape();
}
}
Interfaces of IState would look like this:
public interface IState
{
void Run();
void Swim();
void Fly();
IState ChangeChape();
}
And concrete states look like this:
public class SpiderManState : IState
{
public void Fly()
{
Console.WriteLine("Spiderman is flying");
}
public void Run()
{
Console.WriteLine("Spiderman is running");
}
public void Swim()
{
Console.WriteLine("Spiderman is swimming");
}
public IState ChangeChape()
{
return new IronManState();
}
}
and IronManState would look like this:
public class IronManState : IState
{
public void Fly()
{
Console.WriteLine("IronMan is flying");
}
public void Run()
{
Console.WriteLine("IronMan is running");
}
public void Swim()
{
Console.WriteLine("IronMan is swimming");
}
public IState ChangeChape()
{
return new SpiderManState();
}
}
How does State design pattern satisfy the open closed design principle
Next time when you will want to add new State of Hero, you can add just new class like SomeSuperManState
without editing Hero
class.
So our Hero
class is closed for modification, but it is opened for extension.
CodePudding user response:
The state pattern is typically used as an extension of the strategy pattern that allows the strategy to be executed in steps or phases over multiple calls.
It implements the open/closed principle in the same way that the strategy pattern does.
Think of an executing workflow, which responds to events differently depending on the progress so far and which step is currently pending. When it receives an event, it dispatches it to the current step (the state), and the step takes action that can include changing the current step to one of the following ones.
The alternative to the state pattern is just implementing the whole strategy in a single object that stores internal state. The state pattern is used to divide up the responsibilities and allow the states to be implemented independently. It's also naturally emerges when the state must be persisted between calls.