您的位置:首页 > 编程语言 > Java开发

LintCode_Java旅程 玩具工厂

2017-09-29 10:59 323 查看
礼悟:
公恒学思合行悟,尊师重道存感恩。叶见寻根三返一,江河湖海同一体。
虚怀若谷良心主,愿行无悔给最苦。读书锻炼养身心,诚劝且行且珍惜。

LintCode是一个优秀的平台,值得推荐。平台链接是:http://www.lintcode.com/zh-cn/

题目叙述:

  工厂模式是一种常见的设计模式。请实现一个玩具工厂
ToyFactory
用来产生不同的玩具类。可以假设只有猫和狗两种玩具。

注:给最苦 仅从全部的题目叙述中提取出了重要的部分,想要查看全部的题目叙述,请登录LintCode。

参考代码:

/**
* LintCode 容易 玩具工厂
*
* @author jizuiku
* @version V17.09.29
*/

/**
* Your object will be instantiated and called as such:
* ToyFactory tf = new ToyFactory();
* Toy toy = tf.getToy(type);
* toy.talk();
*/
interface Toy {
void talk();
}

class Dog implements Toy {
// Write your code here
@Override
public void talk() {
// TODO Auto-generated method stub
System.out.println("Wow");
}
}

class Cat implements Toy {
// Write your code here
@Override
public void talk() {
// TODO Auto-generated method stub
System.out.println("Meow");
}
}

public class ToyFactory {
/**
* @param type a string
* @return Get object of the type
*/
public Toy getToy(String type) {
// Write your code here
if ("Dog".equals(type)) {
return new Dog();
} else if ("Cat".equals(type)) {
return new Cat();
} else {
return null;
}
}
}


测试结果:



LintCode,提升技术的优秀平台,推荐。
Java优秀,值得学习。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: