题目地址:
https://www.lintcode.com/problem/toy-factory/description
设计一个工厂类,可以按输入返回对应的Toy。代码如下:
/**
* 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 {
@Override
public void talk() {
System.out.println("Wow");
}
// Write your code here
}
class Cat implements Toy {
@Override
public void talk() {
System.out.println("Meow");
}
// Write your code here
}
public class ToyFactory {
/**
* @param type a string
* @return Get object of the type
*/
public Toy getToy(String type) {
// Write your code here
switch (type) {
case "Dog": return new Dog();
case "Cat": return new Cat();
}
return null;
}
}