题目

工厂模式是一种常见的设计模式。请实现一个玩具工厂 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;
    }
}

 

 

相关文章:

  • 2021-12-24
  • 2021-06-14
  • 2021-12-15
  • 2021-10-25
  • 2021-04-28
  • 2021-04-17
  • 2021-09-22
  • 2022-01-19
猜你喜欢
  • 2021-09-01
  • 2022-02-18
  • 2021-12-24
  • 2022-12-23
  • 2021-09-23
  • 2021-12-02
  • 2021-12-01
相关资源
相似解决方案