您的位置:首页 > 其它

LintCode_496_Toy Factory

2016-04-18 21:49 447 查看
Factory is a design pattern in common usage. Please implement a
ToyFactory
which
can generate proper toy based on the given type.

您在真实的面试中是否遇到过这个题?

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();
*/
interface Toy {
void talk();
}

class Dog implements Toy {
// Write your code here
public void talk(){
System.out.println("Wow");
}
}

class Cat implements Toy {
// Write your code here
public void talk(){
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
Toy toy;
if(type.equals("Cat")){
toy = new Cat();
return toy;
}else if (type.equals("Dog")){
toy = new Dog();
return toy;
}
return null;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: