枚举实现工厂模式

 1 package com. lee.first1200 ;
 2 
 3 public interface Car {
 4 
 5        public void sayName() ;
 6 }
 7 
 8 package com. lee.first1200 ;
 9 
10 public class AudiCar implements Car {
11 
12        @Override
13        public void sayName() {
14              System.out .println( "Audi");
15        }
16 
17 }
18 package com. lee.first1200 ;
19 
20 public class BenzCar implements Car {
21 
22        @Override
23        public void sayName() {
24              System.out .println( "Benz");
25        }
26       
27 }
28 package com. lee.first1200 ;
29 
30 public enum CarFactory {
31 
32       BENZ {
33 
34              @Override
35              public Car create() {
36                    // TODO Auto-generated method stub
37                    return new BenzCar() ;
38              }
39 
40        },
41       AUDI {
42 
43              @Override
44              public Car create() {
45                    // TODO Auto-generated method stub
46                    return new AudiCar() ;
47              }
48 
49        },
50       BMW {
51 
52              @Override
53              public Car create() {
54                    // TODO Auto-generated method stub
55                    return new BmwCar() ;
56              }
57 
58        };
59 
60        public abstract Car create();
61 
62 }
63 
64 package com. lee.first1200 ;
65 
66 public class CarMain {
67 
68        public static void main(String [] args ) {
69             CarFactory .BMW. create(). sayName();
70 
71             CarFactory .AUDI. create(). sayName();
72 
73             CarFactory .BMW. create(). sayName();
74        }
75 }

 

posted @ 2015-10-03 19:07  林本托  阅读(772)  评论(0编辑  收藏  举报