LintCode-[容易] 496. 玩具工厂
来源:互联网 发布:人工智能下一个风口 编辑:程序博客网 时间:2024/04/29 13:28
描述:
工厂模式是一种常见的设计模式。请实现一个玩具工厂 ToyFactory 用来产生不同的玩具类。可以假设只有猫和狗两种玩具。
样例:
ToyFactory tf = ToyFactory();
Toy toy = tf.getToy(‘Dog’);
toy.talk();
输出 Wow
toy = tf.getToy(‘Cat’);
toy.talk();
输出 Meow
思路:
利用多态,将Toy设为抽象基类,Dog和Cat继承Toy,并设计自己的talk函数。getToy函数根据传进去的玩具种类返回相应的子类指针。
C++实现:
/** * 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 virtual void talk() const { cout << "Wow" << endl; }};class Cat: public Toy { // Write your code here virtual void talk() const { cout << "Meow" << endl; }};class ToyFactory {public: /** * @param type a string * @return Get object of the type */ Toy* getToy(string& type) { // Write your code here if (type == "Dog") { Dog* aDog = new Dog; return aDog; } else if (type == "Cat") { Cat* aCat = new Cat; return aCat; } else { return NULL; } }};
阅读全文
0 0
- LintCode-[容易] 496. 玩具工厂
- LintCode:玩具工厂
- lintcode-->玩具工厂
- LintCode之玩具工厂
- 玩具工厂-LintCode
- 496.Toy Factory-玩具工厂(容易题)
- LintCode-玩具工厂(Java工厂模式)
- 玩具工厂
- 玩具工厂
- LintCode算法题解——移动零、玩具工厂、左填充、丑数
- 容易 报数 (lintcode)
- LintCode【容易】A+B
- LintCode【容易】二进制求和
- LintCode(容易)二进制求和
- 容易 将二叉树拆成链表(lintcode)
- LintCode-[容易] 211. 字符串置换
- LintCode-[容易] 491. 回文数
- LintCode-[容易] 539. 移动零
- MyBatis示例---存储过程
- SpringMVC详解(三)------基于注解的入门实例
- C++标准转换运算符reinterpret_cast
- JavaScript 表单验证
- 一分钟告诉你究竟DevOps是什么鬼?
- LintCode-[容易] 496. 玩具工厂
- Comparable接口和Comparator接口
- 激活函数
- 浅谈js
- HDU_6165_ FFF at Valentine
- 今日头条最大点问题
- 直白解读网络编程第一节_文件I/O(入门)
- jupyter notebook简单使用教程
- Revit 其他dll