簡單工廠模式:定義一個工廠類科吭,根據(jù)參數(shù)不同返回不同的類的實例, 被創(chuàng)建的實例通常都有共同的實例 ; 適用于創(chuàng)建對象比較少的場景
示例代碼:
public class Factory {
public Fruit factoryMehtod(String arg) {
if (arg.equals("apple")) {
return new Apple();
} else if (arg.equals("peach")) {
return new Peach();
}
return null;
}
}
public abstract class Fruit {
// 水果名字
String name;
}
public class Apple extends Fruit {
public Apple() {
super();
// TODO Auto-generated constructor stub
System.out.println("生產(chǎn)蘋果");
}
}
public class Peach extends Fruit {
public Peach() {
super();
// TODO Auto-generated constructor stub
System.out.println("生產(chǎn)peach");
}
}
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Factory factory = new Factory();
// 選擇生成蘋果
factory.factoryMehtod("apple");
// 選擇生成桃子
factory.factoryMehtod("peach");
}
}
UML圖例:
簡單工廠模式.png