JAVA基礎(chǔ)23種設(shè)計模式----簡單工廠模式--MonkeyKing
簡單工廠模式屬于類的創(chuàng)建模型模式,又叫靜態(tài)工廠模式。通過專門定義一個類來負責創(chuàng)建其他類的實例,被創(chuàng)建的實例通常都具有共同的父類
- 角色
- 工廠(creator)
- 抽象(product)
- 具體產(chǎn)品(concrete Product)
- 工廠類
- 簡單工廠模式的核心,它負責實現(xiàn)所有創(chuàng)建實例的內(nèi)部邏輯。工廠類可以被外界直接調(diào)用,創(chuàng)建所需的產(chǎn)品對象
- 抽象
- 簡單工廠模式所創(chuàng)建的所有對象的父類,它負責描述所有實例所共有的接口
- 具體產(chǎn)品
- 簡單工廠模式所創(chuàng)建的具體實例對象
具體實現(xiàn)
水果工廠
package simplefactory;
public class FruitFactory {
// public static Fruit getApple() {
// return new Apple();
// }
// public static Fruit getBanana() {
// return new Banana();
// }
public static Fruit getFruit(String type) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
if(type != null) {
Class clazz = Class.forName(type);
return (Fruit) clazz.newInstance();
}else {
return null;
}
}
}
}
抽象水果接口
package simplefactory;
public interface Fruit {
void get();
}
具體水果
package simplefactory;
public class Banana implements Fruit {
public void get() {
System.out.println("get banana");
}
}
package simplefactory;
public class Apple implements Fruit {
public void get() {
System.out.println("get apple");
}
}
實現(xiàn)
package simplefactory;
public class MainClass {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
// Fruit apple = new Apple();
// Fruit banana = new Banana();
//
// apple.get();
// banana.get();
//
// Fruit apple = FruitFactory.getApple();
// Fruit banana = FruitFactory.getBanana();
Fruit apple = FruitFactory.getFruit("Apple");
}
}