加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

[LintCode] Toy Factory

发布时间:2020-12-14 02:14:59 所属栏目:百科 来源:网络整理
导读: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(); -- Wowtoy = tf.getToy('Ca

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读