Java23種設(shè)計(jì)模式--簡(jiǎn)單工廠模式
一枉阵、什么是簡(jiǎn)單工廠模式
- 簡(jiǎn)單工廠模式屬于類的創(chuàng)建型模式,又叫做靜態(tài)工廠方法模式译红。通過(guò)專門定義一個(gè)類來(lái)負(fù)責(zé)創(chuàng)建其他類的實(shí)例,被創(chuàng)建的實(shí)例通常都具有共同的
父類兴溜。
二侦厚、模式中包含的角色及其職責(zé)
1. 工廠(Creator)角色簡(jiǎn)單工廠模式的核心,它負(fù)責(zé)實(shí)現(xiàn)創(chuàng)建所有實(shí)例的內(nèi)部邏輯拙徽。工廠類可以被外界直接調(diào)用刨沦,創(chuàng)建所需的產(chǎn)品對(duì)象。
2. 抽象(Product)角色簡(jiǎn)單工廠模式所創(chuàng)建的所有對(duì)象的父類膘怕,它負(fù)責(zé)描述所有實(shí)例所共有的公共接口想诅。
3. 具體產(chǎn)品(Concrete Product)角色簡(jiǎn)單工廠模式所創(chuàng)建的具體實(shí)例對(duì)象
三、Demo
工廠(Creator)角色
package com.stark.model;
public class FruitFactory{
/**
* 最簡(jiǎn)單的寫法
* @return Fruit的實(shí)例對(duì)象
*/
public static Fruit getApple() {
return new Apple();
}
public static Fruit getBanana() {
return new Banana();
}
/**
* 通過(guò)類型判斷
* @param fruit的實(shí)例對(duì)象
* @return fruit的實(shí)例對(duì)象
*/
public static Fruit getInstance(Fruit fruit) {
if(fruit instanceof Apple) {
return new Apple();
}else if(fruit instanceof Banana){
return new Banana();
}else {
System.out.println("找不到該類");
return null;
}
}
public static Fruit getFruit(String type) {
if(type.equalsIgnoreCase("apple")) {
return new Apple();
}else if (type.equalsIgnoreCase("banana")) {
return new Banana();
}else {
System.out.println("找不到該類");
return null;
}
}
/**
* 演化寫法
* @param type
* @return
* @throws InstantiationException
* @throws IllegalAccessException
*/
public static Fruit createFruit(String type) throws InstantiationException, IllegalAccessException {
if(type.equalsIgnoreCase("apple")) {
return Apple.class.newInstance();
}else if (type.equalsIgnoreCase("banana")) {
return Banana.class.newInstance();
}else {
System.out.println("找不到該類");
return null;
}
}
public static Fruit initFruit(String type) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
Class fruit = Class.forName(type);
return (Fruit) fruit.newInstance();
}
/**
* 最高級(jí)寫法
* @param clazz
* @return
* @throws InstantiationException
* @throws IllegalAccessException
*/
public static Fruit buildFruit(Class<?> clazz) throws InstantiationException, IllegalAccessException {
return (Fruit) clazz.newInstance();
}
}
抽象(Product)角色
package com.stark.model;
public interface Fruit {
void get();
}
具體產(chǎn)品(Concrete Product)角色
package com.stark.model;
public class MainClass {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
Fruit apple = FruitFactory.getInstance(new Apple());
apple.get();
Fruit apples = FruitFactory.buildFruit(Apple.class);
apples.get();
}
}
四岛心、簡(jiǎn)單工廠模式的優(yōu)缺點(diǎn)
在這個(gè)模式中来破,工廠類是整個(gè)模式的關(guān)鍵所在。它包含必要的判斷
邏輯忘古,能夠根據(jù)外界給定的信息徘禁,決定究竟應(yīng)該創(chuàng)建哪個(gè)具體類的
對(duì)象。用戶在使用時(shí)可以直接根據(jù)工廠類去創(chuàng)建所需的實(shí)例髓堪,而無(wú)
需了解這些對(duì)象是如何創(chuàng)建以及如何組織的送朱。有利于整個(gè)軟件體系
結(jié)構(gòu)的優(yōu)化。不難發(fā)現(xiàn)干旁,簡(jiǎn)單工廠模式的缺點(diǎn)也正體現(xiàn)在其工廠類上驶沼,由于工廠類集中
了所有實(shí)例的創(chuàng)建邏輯,所以“高內(nèi)聚”方面做的并不好争群。另外商乎,當(dāng)系統(tǒng)中的
具體產(chǎn)品類不斷增多時(shí),可能會(huì)出現(xiàn)要求工廠類也要做相應(yīng)的修改祭阀,擴(kuò)展
性并不很好鹉戚。