State Design Pattern

            In keeping with my recent learning about Java Design Patterns, as outlined by the Gang of Four, I have recently been doing research on the State Design Pattern. I came across an extremely useful article which details the Design Pattern logic, implementation, upsides and downsides, as well as giving an overall evaluation. The article is titled “State Design Pattern in Java,” by Denis Szczukocki, and starts by explaining that the main usage for the State pattern is “to allow the object for changing its behavior without changing its class.” It is also cleaner than a project cluttered with if/else statements for controlling object behavior. The basis is that an object who’s behavior is dependent on a specific state can easily change states and therefore change behaviors without the creation of a new object and the classes responsible for this behavior will be “tightly coupled.” Within the pattern, there will be 2 essential classes and a number of extra classes dependent on the number of states required. The first is the context class. The context class delegates object behavior to the other class, the state class, but the context class is the one used by the client. The state class is usually an interface, with the concrete state classes implementing this interface and dictating behavior. The article gives the example of a package with 3 states: ordered, delivered, and received. There is a package class, which is the context class, and contains methods to move to the next/previous states and print the status as well. When an instance of the package class is created, really what happens is that an instance of the first state (ordered is created). When ready, the package object can move to the delivered state, and then the received state, all of which have different behaviors. The three behaviors in the PackageState interface common to all concrete states are next, previous, and printStatus, each which has a different behavior depending on the concrete class of the package. The article then notes that a possible downside to the State design pattern is that, “the state becomes hardcoded, which is a bad practice in general.” This taught me how to use the State Design Pattern and why it is good practice. I plan to use this in future projects when I can in order to practice, as well as to implement good project design practice. It is understandable and not terribly difficult to implement, so I know this can help me in my future work. 

Source: https://www.baeldung.com/java-state-design-pattern

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: