• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

xxxqqq

  • 博客园
  • 联系
  • 订阅
  • 管理

View Post

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 }

 

posted on 2017-05-10 13:58  xxxqqq  阅读(373)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3