State design pattern in Java

State design pattern in Java


State pattern can be used when we want
to change the behavior of an object depending on some internal state like
depending on the current state of the mobile phone may either ring or vibrate
let’s jump into code and check how to implement it our mobile class will be our client
class we will come to this later we will have an interface mobile alert state
and have an abstract method alert so any implementation class will have the
required business logic inside alert method in mobile context class we will
set the current state of the mobile like ringing or silent or vibration so we will create a new ringing class
and make it the default State let us create a ringing class and
implement mobile alert state and on alert function we will print
mobile is ringing coming back to mobile context we need to
provide a mechanism to set other state to the mobile like vibrate or silent and on alert method we will call that
respective alert method of the state object so in our client class let’s create a
mobile context object and when we run mobile context.alert
by default it is set to ringing let’s create other state type silent and print mobile is in silent mode and in mobile class we will set the
state to silent object and mobile context.alert will execute
silent.alert method and again we will reset it to ringing once we run the application we can see
the behavior of the mobile gets changed depending on the current state because
when the state is silent mobile context.alert calls silent.alert and
logs mobile is in silent mode again when the state is changed to ringing
mobile context.alert calls ringing.alert function this is a simple
example of state design pattern that’s all for this tutorial see you again in
next design pattern tutorials don’t forget to hit the like button and
subscribe for upcoming video tutorials see you next time

Leave a Reply

Your email address will not be published. Required fields are marked *