// This code illustrates the use of a factory method // to hide the details of subclasses from the user. // Note random use of override & final for teaching purposes. #include #include using namespace std; class Dog { public: static Dog *create(double weight, const string &name); // Factory method Dog(const string &n) : name(n) {} virtual ~Dog() = default; string who() const { return name; } virtual string bark() const = 0; virtual string breed() const = 0; private: const string name; // MUST use member initialization. }; class Chihuahua : public Dog { public: Chihuahua(const string &n) : Dog(n) {} ~Chihuahua() {} string bark() const { return "¡yip!"; } string breed() const { return "Chihuahua"; } }; class Beagle : public Dog { public: Beagle(const string &n) : Dog(n) {} ~Beagle() = default; string bark() const override { return "bow wow"; } string breed() const final { return "beagle"; } }; class GreatDane : public Dog { public: GreatDane(const string &n) : Dog(n) {} ~GreatDane() = default; string bark() const override final { return "WOOF‼‼"; } string breed() const { return "Great Dane"; } }; // Factory method! Dog *Dog::create(double weight, const string &name) { if (weight < 10) return new Chihuahua(name); if (weight > 80) return new GreatDane(name); return new Beagle(name); } // No user code, below, mentions any class but Dog. // If we were to add more cases to Dog::Create(), we wouldn’t // need to recompile main(). int main() { Dog *a = Dog::create(4, "Ren"); Dog *b = Dog::create(15, "Snoopy"); const Dog *c = Dog::create(120, "Scooby-Doo"); cout << a->who() << " the " << a->breed() << " says " << a->bark() << '\n' << b->who() << " the " << b->breed() << " says " << b->bark() << '\n' << c->who() << " the " << c->breed() << " says " << c->bark() << '\n'; delete a; delete b; delete c; }