题目地址:
https://www.lintcode.com/problem/toy-factory/description
要求设计一个工厂类,可以根据输入参数来决定初始化哪个对象。
代码如下:
interface Toy {
void talk();
}
class Dog implements Toy {
// Write your code here
@Override
public void talk() {
System.out.println("Wow");
}
}
class Cat implements Toy {
// Write your code here
@Override
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
switch (type) {
case "Dog": return new Dog();
case "Cat": return new Cat();
default: return null;
}
}
}
时空复杂度 O ( 1 ) O(1) O(1)。