工厂模式是一种常见的设计模式。请实现一个玩具工厂 ToyFactory 用来产生不同的玩具类。可以假设只有猫和狗两种玩具。
您在真实的面试中是否遇到过这个题?
Yes
样例
ToyFactory tf = ToyFactory();
Toy toy = tf.getToy('Dog');
toy.talk();
Wow
toy = tf.getToy('Cat');
toy.talk();
Meow
/**
* Your object will be instantiated and called as such:
* ToyFactory* tf = new ToyFactory();
* Toy* toy = tf->getToy(type);
* toy->talk();
*/
class Toy {
public:
virtual void talk() const = 0;
};
class Dog : public Toy {
// Write your code here
public:
void talk() const {
cout << "Wow" << endl;
}
};
// 基类中又const ,那么继承的派生类中必须要又const ,否则编译不通过
class Cat : public Toy {
// Write your code here
public:
void talk() const {
cout << "Meow" << endl;
}
};
// 基类中又const ,那么继承的派生类中必须要又const ,否则编译不通过
class ToyFactory {
public:
/**
* @param type a string
* @return Get object of the type
*/
Toy* getToy(string& type) {
// Write your code here
Toy * t;
if (type == "Dog") {
t = new Dog();
return t;
}
if (type == "Cat") {
t = new Cat();
return t;
}
return NULL;
}
};