java编程思想读书笔记340页工厂模式

来源:互联网 发布:淘宝无线店铺链接 编辑:程序博客网 时间:2024/05/19 19:59

47行的参数的作用:按照22行产生一个新的类。
之后,47行调用函数serviceConsumer,
这个方法的定义在41行,
然后执行42行,
47行和41行,相当于:ServiceFactory fact=new Implementation1Factory()
所以,42行调用的getService()是implementation1Factory中的,即23行和24行。
22行的类调用23行的方法
24行返回一个Implementation1的类
所以,42行的s是Implementation1的类。
42行和24行相当于:Service s=new Implementation1()
所以,43行和44行用的是15行和16行的方法。


1)         import static net.mindview.util.Print.*;
2)        
3)         interface Service{
4)         void method1();
5)         void method2();
6)         }
7)        
8)         interface ServiceFactory{
9)         Service getService();
10)         }
11)        
12)         import static net.mindview.util.Print.*;
13)         class Implementation1 implements Service{
14)         Implementation1(){}
15)         public void method1(){print("Implementation1 method1");}
16)         public void method2(){print("Implementation1 method2");}
17)        
18)         }
19)        
20)         import static net.mindview.util.Print.*;
21)        
22)         class Implementation1Factory implements ServiceFactory{
23)         public Service getService(){
24)         return new Implementation1();
25)         }
26)         }
27)        
28)         class Implementation2 implements Service{
29)         Implementation2(){}
30)         public void method1(){print("Implementation2 method1");}
31)         public void method2(){print("Implementation2 method2");}
32)         }
33)        
34)         class Implementation2Factory implements ServiceFactory{
35)         public Service getService(){
36)         return new Implementation2();
37)         }
38)         }
39)        
40)         public class Factories{
41)         public static void serviceConsumer(ServiceFactory fact){
42)         Service s=fact.getService();
43)         s.method1();
44)         s.method2();
45)         }
46)         public static void main(String[] args){
47)         serviceConsumer(new Implementation1Factory());
48)         serviceConsumer(new Implementation2Factory());
49)         }
50)         }