簡單工廠模式
一、什麼是簡單工廠模式
簡單工廠模式屬於類的創建型模式,又叫做靜態工廠方法模式。通過專門定義一個類來負責創建其他類的實例,被創建的實例通常都具有共同的父類。
二、模式中包含的角色及其職責
1.工廠(Creator)角色
簡單工廠模式的核心,它負責實現創建所有實例的內部邏輯。工廠類可以被外界直接調用,創建所需的產品對象。
2.抽象(Product)角色
簡單工廠模式所創建的所有對象的父類,它負責描述所有實例所共有的公共接口。
3.具體產品(Concrete Product)角色
簡單工廠模式所創建的具體實例對象
在這個模式中,工廠類是整個模式的關鍵所在。它包含必要的判斷
邏輯,能夠根據外界給定的信息,決定究竟應該創建哪個具體類的
對象。用戶在使用時可以直接根據工廠類去創建所需的實例,而無
需瞭解這些對象是如何創建以及如何組織的。有利於整個軟件體系
結構的優化。
不難發現,簡單工廠模式的缺點也正體現在其工廠類上,由於工廠類集中
了所有實例的創建邏輯,所以“高內聚”方面做的並不好。另外,當系統中的
具體產品類不斷增多時,可能會出現要求工廠類也要做相應的修改,擴展
性並不很好。
四、代碼演示
package org.fbm.simplefactory;
//抽象類,水果
public interface Fruit {
public void get();
}
package org.fbm.simplefactory;
//具體產品(Concrete Product)角色
public class SimpleFactory {
//第一種實現方法
public static Fruit getApple(){
return new Apple();
}
public static Fruit getBanana(){
return new Banana();
}
//第二種實現的方法
public static Fruit getFruitTwo(String type) {
try{
if(type.equalsIgnoreCase("apple")){
return Apple.class.newInstance();
}
if(type.equalsIgnoreCase("banana")){
return Banana.class.newInstance();
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
//第三種實現方式
public static Fruit getFruitThree(String type) throws ClassNotFoundException, InstantiationException, IllegalAccessException{
Class<?> fruit = Class.forName(type);
return (Fruit) fruit.newInstance();
}
}
package org.fbm.simplefactory;
//具體產品(Concrete Product)角色,蘋果類
public class Apple implements Fruit {
@Override
public void get() {
System.out.println("我愛吃蘋果");
}
}
package org.fbm.simplefactory;
//具體產品(Concrete Product)角色,香蕉類
public class Banana implements Fruit {
@Override
public void get() {
System.out.println("我愛吃香蕉");
}
}
package org.fbm.simplefactory;
//客戶端調用
public class MainClass {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
Fruit apple1=SimpleFactory.getFruitTwo("apple");
Fruit banana1=SimpleFactory.getFruitTwo("banana");
apple1.get();
banana1.get();
Fruit apple2=SimpleFactory.getFruitThree("org.fbm.simplefactory.Apple");
Fruit banana2=SimpleFactory.getFruitThree("org.fbm.simplefactory.Banana");
apple2.get();
banana2.get();
Fruit apple3=SimpleFactory.getApple();
Fruit banana3=SimpleFactory.getBanana();
apple3.get();
banana3.get();
}
}