Toy Factory

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

加了一个Enum来表示不用的ToyType; 可以不加直接上String
 1 /**
 2  * Your object will be instantiated and called as such:
 3  * ToyFactory tf = new ToyFactory();
 4  * Toy toy = tf.getToy(type);
 5  * toy.talk();
 6  */
 7 interface Toy {
 8     void talk();
 9 }
10 
11 
12 class Dog implements Toy {
13     // Write your code here
14     @Override
15     public void talk(){
16         System.out.println("Wow");
17     }
18 }
19 
20 class Cat implements Toy {
21     // Write your code here
22     @Override
23     public void talk(){
24         System.out.println("Meow");
25     }
26 }
27 
28 public class ToyFactory {
29     /**
30      * @param type a string
31      * @return Get object of the type
32      */
33     public Toy getToy(String type) {
34         // Write your code here
35         ToyType t = ToyType.fromString(type);
36         switch (t){
37             case DOG: return new Dog();
38             case CAT: return new Cat();
39             default: return null;
40         }
41     }
42     
43     public enum ToyType {
44 
45         DOG("Dog"), CAT("Cat"), UNKNOWN("UNKNOWN");
46     
47         private String name;
48     
49         private ToyType(String name) {
50             this.name = name;
51         }
52     
53         public static ToyType fromString(String name) {
54             for (ToyType toyType : ToyType.values()) {
55                 if (toyType.getName().equals(name)) {
56                     return toyType;
57                 }
58             }
59             return UNKNOWN;
60         }
61         
62         private String getName(){
63             return name;
64         }
65     }
66 }
原文地址:https://www.cnblogs.com/xinqiwm2010/p/6835626.html