[LintCode] Toy Factory

347 查看

Problem

Factory is a design pattern in common usage. Please implement a ToyFactory which can generate proper toy based on the given type.

Example


ToyFactory tf = ToyFactory();
Toy toy = tf.getToy('Dog');
toy.talk(); 
-->> Wow

toy = tf.getToy('Cat');
toy.talk();
-->> Meow

Note

系统设计基础题,用class Dog和class Cat继承interface Toy,然后在ToyFactory里按照String type生成需要的类就可以了。

Solution

interface Toy {
    void talk();
}

class Dog implements Toy {
    public void talk() {
        System.out.println("Wow");
    }
}

class Cat implements Toy {
    public void talk() {
        System.out.println("Meow");
    }
}

public class ToyFactory {
    public Toy getToy(String type) {
        Toy T = null;
        if (type.equals("Dog")) T = new Dog();
        else if (type.equals("Cat")) T = new Cat();
        return T;
    }
}