Last active
February 14, 2024 10:26
-
-
Save kenpower/b8a30cde0202ae9a182abda037a47742 to your computer and use it in GitHub Desktop.
Null Object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
class ChaseStrategy{ | |
public: | |
virtual void chase() = 0; | |
}; | |
class RandomChase : public ChaseStrategy { | |
void chase() override { | |
std::cout << "Randomly wander around\n"; | |
} | |
}; | |
class DirectedChase : public ChaseStrategy { | |
void chase() override { | |
std::cout << "If I see target, move towards it\n"; | |
} | |
}; | |
class NullChase : public ChaseStrategy { | |
void chase() override { | |
// do nothing | |
} | |
}; | |
NullChase nullChase; | |
class Ghost { | |
ChaseStrategy* chaseStrategy; | |
public: | |
Ghost():chaseStrategy(&nullChase) {} | |
void set(ChaseStrategy* newstrategy) { | |
chaseStrategy = newstrategy; | |
} | |
void doIt() { | |
chaseStrategy->chase(); //safe because of null object | |
} | |
}; | |
int main() | |
{ | |
Ghost pinky; | |
pinky.doIt(); | |
pinky.set(new DirectedChase); | |
pinky.doIt(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
class ChaseStrategy{ | |
public: | |
virtual void chase() = 0; | |
}; | |
class RandomChase : public ChaseStrategy { | |
void chase() override { | |
std::cout << "Randomly wander around\n"; | |
} | |
}; | |
class DirectedChase : public ChaseStrategy { | |
void chase() override { | |
std::cout << "If I see target, move towards it\n"; | |
} | |
}; | |
class Ghost { | |
ChaseStrategy* chaseStrategy; | |
public: | |
Ghost() {} | |
void set(ChaseStrategy* newstrategy) { | |
chaseStrategy = newstrategy; | |
} | |
void doIt() { | |
if(chaseStrategy != null) // better check! | |
chaseStrategy->chase(); | |
} | |
}; | |
int main() | |
{ | |
Ghost pinky; | |
pinky.doIt(); // no strategy yet, be carefull! | |
pinky.set(new DirectedChase); | |
pinky.doIt(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment