Πέμπτη, 16 Ιουλίου 2020

State Pattern (OOP)

The state pattern change behaviour of StateContext, changing the internal state pointer to a state type object, depending on state. Here the writeName  return Nill or a State pointer and we check this and if it is a state object we change it.


class State {
      Function writeName (name$) {
            Error "Abstract"
      }
}

class LowerCaseState as State {
      Function writeName (name$) {
            Print Lcase$(name$)
            =pointer(MultipleUpperCaseState())
      }
}

class MultipleUpperCaseState as State {
Private:
      count = 0
Public:      
      Function writeName (name$) {
            Print Ucase$(name$)
            .count++
            if .count=2 Then
                  =Pointer(LowerCaseState())
                  .count<=0
            else
                  =Pointer()
            End if
      }
}

class StateContext {
private:      
      state=pointer()
public:
      module writeName(name$) {
            what=.state=>writeName(name$)
            if what is type state then .state<=what
             }
class:
      module StateContext {
            .state->LowerCaseState()
      }
}
Module StateDemo {
      context=StateContext()
      context.writeName "Monday"
      context.writeName "Tuesday"
      context.writeName "Wednesday"
      context.writeName "Thursday"
      context.writeName "Friday"
      context.writeName "Saturday"
      context.writeName "Sunday"
}
StateDemo

Δεν υπάρχουν σχόλια:

Δημοσίευση σχολίου