What is the need for State Pattern in C#?

If you want to change behavior of an object when there is a change in its internal state then you can do it by implementing State pattern in your C# application.

Here is a code sample for it:

abstract class stateClass {
public void abstract handleRequest(contextClass conObj);
}
class derivedClass1:stateClass {
public override void handleRequest(contextClass conObj) {
conObj.objState = new derivedClass2();
}
}
class derivedClass2:stateClass {
public override void handleRequest(contextClass conObj) {
conObj.objState = new derivedClass1();
}
}
class contextClass {
public stateClass objState;
//Include constructor accepting stateClass instance as parameter and set it to objState
//Include property to get/set objState
public void raiseRequest() {
objState.handleRequest(this);
}
}

Now you can create a new class and inside its Main method, you can create an instance of contextClass (by calling constructor passing either instance of derivedClass1 or derivedClass2) and call the raiseRequest method, every call to this method toggles the object’s state.

| What is the need for Bridge Pattern in C#? | What is the need for Builder Pattern in C#? | What is the need for Chain of Responsibility Pattern in C#? | What is the need for Command Pattern in C#? | What is the need for Composite Pattern in C#? | What is the need for Decorator Pattern in C#? | What is the need for Flyweight Pattern in C#? | What is the need for Interpreter Pattern in C#? | What is the need for Iterator Pattern in C#? | What is the need for Mediator Pattern in C#? | What is the need for Memento Pattern in C#? | What is the need for Prototype Pattern in C#? | What is the need for State Pattern in C#? | What is the need for Strategy Pattern in C#? | What is the need for Template Method Pattern in C#? | What is the need for unsafe code in C#? | What is the purpose of assert() in C#? | What is the purpose of AutoResetEvent in .NET? | What is the purpose of Console.ReadLine() in C#? | What is the purpose of machine.config file in .NET? |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.