工厂设计模式

 

 

 1 public class FactoryMethod {
 2 
 3     public static void main(String[] args) {
 4         // 使用者和被使用者两者之间耦合,产生了依赖,当被使用者产生改变时,会影响使用者
 5         //使用工厂模式来降低两者之间的依赖.
 6         Product phone = ProductFactory.getProduct("computer");
 7         assert phone != null;
 8         phone.work();
 9     }
10 
11 }
12 
13 class ProductFactory{
14     public static Product getProduct(String name) {
15         if("phone".equals(name)) {
16             return new Phone();
17         }else if ("computer".equals(name)) {
18             return new Computer();
19         }else {
20             return null;
21         }
22     }
23 }
24 
25 interface Product{
26     public void work();
27 }
28 class Phone implements Product{
29     @Override
30     public void work() {
31         // TODO Auto-generated method stub
32         System.out.println("手机开始工作...");
33     }
34 }
35 class Computer implements Product{
36 
37     @Override
38     public void work() {
39         // TODO Auto-generated method stub
40         System.out.println("电脑开始工作...");
41     }
42     
43 }

 

posted @ 2016-11-08 16:02  X-POWER  阅读(1282)  评论(0编辑  收藏  举报