Author - StudySection Post Views - 181 views
PYTHON

STATE DESIGN PATTERN IN PYTHON

INTRODUCTION

The state design pattern is used when working with objects that go through a variety of states over their lifetime and respond to requests (or change states) based on their current state.

If the state pattern is not used in this situation, the code base will wind up being needlessly complicated, and difficult to maintain due to a large number of conditional blocks. Problems where an object should alter its behavior when its internal state changes are solved using the state pattern.

REAL-WORLD EXAMPLE

Take a car for example.
We can change the state of the car. We can use the brakes to slow it down or stop the car and the accelerators to accelerate it up. But the state of the car will change or not depending on the current state of the car. If the car’s engine is started, we can Off it or we can use an accelerator to move the car or we can use the break to stop the car. But if the car’s engine is not yet started or it is OFF, nothing will go to happen if we press the accelerator or breaks it. For a stopped car only possible next state is to ON /start the car’s engine.

Components:

  • Context: Describes an interface for the client to connect. It keeps track of links to concrete state objects.
  • Concrete States: classes that include state-specific functionality
  • States: Specifies the actions that each state must do.

EXAMPLE
PATTERN

PATTERN1

OUTPUT

Advantages:

  1. We can add as many states as we want to the context without changing the other states that already exist.
  2. We do not have to write a large number of conditional blocks for switching between the states.

Disadvantages:

  1. If there are few states, it would not be feasible to use this pattern as it would lead to inessential code.
  2. We should use the state design patterns only if states have complicated logic and state changes often, else it will complicate easy things with too many classes and objects

If you need to prove your skills in the .NET framework, get .NET certified on StudySection. StudySection provides .NET certification exam for beginners as well as experts in the .NET framework. This .NET certification can improve your resume’s success rate.

Leave a Reply

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

fiteesports.com rivierarw.com cratosroyalbet betwoon grandpashabet grandpashabet giriş deneme bonusu veren siteler casino siteleri