设计模式2:工程模式(1)

  什么是工厂模式?

  提供一个创建一系列或相互依赖对象的接口,而不需指定它们具体的类。

  通俗的讲就是定义了多个产品的类,且只有一个工厂类,而这个工厂类根据需求的不同,可以产生不同产品类的对象。

 

  作用:主要为创建对象提供过度接口,以便将创建对象的具体过程屏蔽隔离起来,提高灵活性。

  示例:

  

 1 import java.util.*;
 2 class  Factory  //厨房
 3 {
 4     public static IEat cook(int choose){    
 5         IEat i = null;
 6         switch(choose){
 7             case 1:
 8                 i = new Duck();                
 9                 break;
10             case 2:
11                 i = new Chicken();                
12                 break;
13             case 3:
14                 i = new Fish();                
15                 break;
16             case 4 :
17                 i = new Pig();                
18                 break;
19             case 5:
20                 i = new Beef();
21                 break;
22         }
23         return i;
24     }
25 
26     //饭店入口
27     public static void main(String[] args) 
28     {
29         Scanner input = new Scanner(System.in);
30         System.out.println("吃啥?1 烤鸭   2 炸鸡  3 水煮鱼  4 烤乳猪 5 烤牛排");
31         int choose = input.nextInt();
32         IEat i = Factory.cook(choose);
33         i.eat();
34         System.out.println("欢迎下次光临!!!");
35 
36     }
37 }
38 interface IEat
39 {
40     void eat();  //
41 }
42 class Duck implements IEat
43 {
44     public void eat(){
45         System.out.println("吃烤鸭");
46     }
47 }
48 class Chicken implements IEat
49 {
50     public void eat(){
51         System.out.println("吃炸鸡");
52     }
53 }
54 
55 class Fish implements IEat
56 {
57     public void eat(){
58         System.out.println("吃水煮鱼");
59     }
60 }
61 class Pig implements IEat
62 {
63     public void eat(){
64         System.out.println("吃烤乳猪");
65     }
66 }
67 class Beef implements IEat
68 {
69     public void eat(){
70         System.out.println("吃牛排");
71     }
72 }

 

  未完,待续。

posted on 2015-09-12 20:23  AellenLei  阅读(472)  评论(0编辑  收藏  举报

导航