码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode:玩具工厂

时间:2016-07-07 17:28:56      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

题目

工厂模式是一种常见的设计模式。请实现一个玩具工厂 ToyFactory 用来产生不同的玩具类。可以假设只有猫和狗两种玩具。

样例
ToyFactory tf = ToyFactory();
Toy toy = tf.getToy(‘Dog‘);
toy.talk(); 
>> Wow

toy = tf.getToy(‘Cat‘);
toy.talk();
>> Meow
解题
/**
 * Your object will be instantiated and called as such:
 * ToyFactory tf = new ToyFactory();
 * Toy toy = tf.getToy(type);
 * toy.talk();
 */
interface Toy {
    void talk();
}

class Dog implements Toy {
    // Write your code here
    public void talk(){
        System.out.println("Wow");
    }
}

class Cat implements Toy {
    // Write your code here
    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
        if(type.equals("Dog")){
            return new Dog();
        }
        if(type.equals("Cat")){
            return new Cat();
        }
        return null;
    }
}

 

 

lintcode:玩具工厂

标签:

原文地址:http://www.cnblogs.com/theskulls/p/5650716.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!