JAVA基礎(chǔ)23種設(shè)計(jì)模式----簡(jiǎn)單工廠模式--MonkeyKing
簡(jiǎn)單工廠模式屬于類的創(chuàng)建模型模式尼夺,又叫靜態(tài)工廠模式。通過(guò)專門(mén)定義一個(gè)類來(lái)負(fù)責(zé)創(chuàng)建其他類的實(shí)例扔枫,被創(chuàng)建的實(shí)例通常都具有共同的父類
- 角色
- 工廠(creator)
- 抽象(product)
- 具體產(chǎn)品(concrete Product)
- 工廠類
- 簡(jiǎn)單工廠模式的核心腰鬼,它負(fù)責(zé)實(shí)現(xiàn)所有創(chuàng)建實(shí)例的內(nèi)部邏輯赐稽。工廠類可以被外界直接調(diào)用,創(chuàng)建所需的產(chǎn)品對(duì)象
- 抽象
- 簡(jiǎn)單工廠模式所創(chuàng)建的所有對(duì)象的父類党瓮,它負(fù)責(zé)描述所有實(shí)例所共有的接口
- 具體產(chǎn)品
- 簡(jiǎn)單工廠模式所創(chuàng)建的具體實(shí)例對(duì)象
具體實(shí)現(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");
}
}
實(shí)現(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");
}
}