[LintCode] Toy Factory

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;
    }
}

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...