State Design Pattern in Visual Basic .NET

Definition

The State Design Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change
its class.

State Design Pattern is one of the Behavioral Design Patterns. Some objects may have several states in its life cycle, and also it has different behavior depending on the state where the object lives. In such cases you can use State Design Patter

First of all we will see the UML diagram for State Design Pattern
State Design Pattern UML diagram

Participants

Context

  • Provide interface to client
  • Keep track of the current state which is an instance of the ConcreteSate

State
This is the interface which defines all the states of the Context class
Concrete State
You can have sub class for each state. Each state has different behaviors

Example

We will see an example to understand State Design Pattern and implement it in VB.NET

A file can have three different states Open,Close,Delete. If file is opened you can not delete it but you can close it. If file is closed you can open it or you can delete it. If file is deleted you can not open it or you can not close it

To implement above example we can use the following UML diagram

Here File is the Context .

Now we will see how we can code this State Design Pattern in VB.NET

File (context) Class

State Interface

DeleteState Concrete Class

OpenState Concrete Class

 

CloseState Concrete Class

Now you can test the above code with following code

Finally, you will see the following output

 

Leave a Reply

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