设计模式之工厂模式

工厂模式

工厂模式,即拥有创造能力的一种设计模式,既然是创造,应该具备根据不同的材料,输出不同的产品,下面以创造男孩和女孩为例,简单介绍下工厂模式。

背景

不论是boy还是girl,都属于human的范畴,都具有human共有的特性,比如听说读写,吃喝玩耍等能力。废话少说,上类图。

类图

factory-design-pattern

Java code

 1 interface Human {
 2     public void Talk();
 3     public void Walk();
 4 }
 5  
 6  
 7 class Boy implements Human{
 8     @Override
 9     public void Talk() {
10         System.out.println("Boy is talking...");        
11     }
12  
13     @Override
14     public void Walk() {
15         System.out.println("Boy is walking...");
16     }
17 }
18  
19 class Girl implements Human{
20  
21     @Override
22     public void Talk() {
23         System.out.println("Girl is talking...");    
24     }
25  
26     @Override
27     public void Walk() {
28         System.out.println("Girl is walking...");
29     }
30 }
31  
32 public class HumanFactory {
33     public static Human createHuman(String m){
34         Human p = null;
35         if(m == "boy"){
36             p = new Boy();
37         }else if(m == "girl"){
38             p = new Girl();
39         }
40  
41         return p;
42     }
43 }
View Code
原文地址:https://www.cnblogs.com/RobertC/p/3502434.html