Τρίτη, 14 Ιουλίου 2020

Strategy Pattern (OOP)

Robot can change behaviour by changing an inner group in R2 group, using a class type as IBehaviour.



class IBehaviour {
      function moveCommand() {
            error "abstract"
      }
}


class AgressiveBehaviour as IBehaviour {
      function moveCommand() {
            Print "Agressive Behaviour: if find another robot attack it"
            =1
      }
}


class DefensiveBehaviour as IBehaviour {
      function moveCommand() {
            Print "Defensive Behaviour: if find another robot run from it"
            =-1
      }
}


class NormalBehaviour as IBehaviour {
      function moveCommand() {
            Print "Normal Behaviour: if find another robot ignore it"
            =0
      }
}


class Robot {
Private:
      IBehaviour behaviour
Public:
      property name$ {value}
      module setBehaviour (b as IBehaviour) {
            .behaviour<=b
      }
      function getBehaviour() {
            =.behaviour
      }
      module move {
            message$="Selection:"+Str$(.behaviour.moveCommand())+" for Robot "+.[name]$
            Print message$
      }
class:
      module Robot (.[name]$) {
            .behaviour<=NormalBehaviour()
      }
}
R1=Robot("R2")
R1.move
R1.setBehaviour AgressiveBehaviour()
R1.move
R1.setBehaviour DefensiveBehaviour()
R1.move

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

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