Skip to content

Instantly share code, notes, and snippets.

@kenpower
Last active February 14, 2024 10:26
Show Gist options
  • Save kenpower/b8a30cde0202ae9a182abda037a47742 to your computer and use it in GitHub Desktop.
Save kenpower/b8a30cde0202ae9a182abda037a47742 to your computer and use it in GitHub Desktop.
Null Object
#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();
}
#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