Pregunta

A part of my programming assignment needs parsing a String using the State Pattern. It is explicitly requested that the State Pattern is used, so no other option is allowed.

An example String is: "update user filter userId=user3 set name=xxx". (The bold ones are keywords).

The request is like follows:

While parsing the query you should use State Pattern. There are four states: OPERATOR, OBJECT, FILTER and VALUES.

I looked examples about State Pattern, I think I got it, but I couldn't be able to figure out how to apply it to string parsing.

I'll be glad if someone gives me some hints.

¿Fue útil?

Solución

First create your state interface. Perhaps with one method: parse

Create your 4 concrete states. Implement each to parse only its part of the string, Your context will be in responsibility to split the string and change states.

In Your context class you do the following:

  • You know that the OperatorState is always the first one, so init
  • you context's state to it. Read the string until you reach the next
  • keyword ("filter") Move that string you've read to the current state (Opearator)
  • Change the current state to the next one (FilterState)

And so on...

If you understand the state pattern then this should be enough to build a solution.

Note: You can have a dictionary with keywords and states so you can automate it, but in your case i think a simple solution is enough.

Good Luck

Otros consejos

I might be misunderstanding what you mean by state pattern, so if i get this wrong then ignore me,

let's say you're looking for the string "abac"

you start with the empty state "" and iterate down the characters of the string. if you get an 'a' you go to state "a" get a 'b', go to state "ab", get 'a', you go back to state "a", anything else to the empty state, etc

once you get to state "abac" you've found your string. It's a simple DFA to find a regular expression.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top