[LintCode] Toy Factory

前端之家收集整理的这篇文章主要介绍了[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;
    }
}
原文链接:https://www.f2er.com/javaschema/283973.html

猜你在找的设计模式相关文章