概念:簡(jiǎn)單工廠模式通俗的講就是一個(gè)類(lèi)的工廠,用于生產(chǎn)類(lèi),而這個(gè)工廠本身就是一個(gè)類(lèi),他可以創(chuàng)建多個(gè)類(lèi)的實(shí)例。
下面我們就來(lái)實(shí)現(xiàn)一個(gè)簡(jiǎn)單工廠模式。
場(chǎng)景:Android開(kāi)發(fā)中,我們必然會(huì)調(diào)用接口,而接口地址要做測(cè)試環(huán)境和正式環(huán)境的切換,甚至需要在多個(gè)測(cè)試環(huán)境和多個(gè)正式環(huán)境中,那么接口地址就有多個(gè)。
普通的做法:直接將接口地址放在靜態(tài)常量中保存,通過(guò)注釋來(lái)切換接口地址或通過(guò)標(biāo)識(shí)來(lái)判斷環(huán)境選擇正確的地址。
實(shí)踐:通過(guò)簡(jiǎn)單工廠模式來(lái)完成配置。
1. 創(chuàng)建app接口地址基礎(chǔ)類(lèi)
package net.yibee.instantMessage;
/**
* 基本功能:app 接口地址基礎(chǔ)類(lèi)
* Created by wangjie on 2017/4/14.
*/
public class AppInterfaceUrlOperation {
public String getAppInterfaceUrl() {
return "";
}
}
2.創(chuàng)建測(cè)試環(huán)境接口地址管理類(lèi)
package net.yibee.instantMessage;
import net.yibee.utils.Constants;
/**
* 基本功能:線(xiàn)上環(huán)境
* Created by wangjie on 2017/4/14.
*/
public class AppInterfaceUrlOperationOnLine extends AppInterfaceUrlOperation{
@Override
public String getAppInterfaceUrl() {
return Constants.ONLINEURL;
}
}
3.創(chuàng)建線(xiàn)下接口地址管理類(lèi)
package net.yibee.instantMessage;
import net.yibee.utils.Constants;
/**
* 基本功能:線(xiàn)下環(huán)境
* Created by wangjie on 2017/4/14.
*/
public class AppInterfaceUrlOperationLine extends AppInterfaceUrlOperation {
@Override
public String getAppInterfaceUrl() {
return Constants.LINEURL;
}
}
4.創(chuàng)建工廠類(lèi)
package net.yibee.instantMessage.factory;
import net.yibee.instantMessage.AppInterfaceUrlOperation;
import net.yibee.instantMessage.AppInterfaceUrlOperationLine;
import net.yibee.instantMessage.AppInterfaceUrlOperationOnLine;
import net.yibee.utils.Constants;
/**
* 基本功能:app 接口地址工廠
* Created by wangjie on 2017/4/14.
*/
public class AppInterfaceUrlOperationFactory {
public static AppInterfaceUrlOperation createAppInterfaceUrlperation() {
AppInterfaceUrlOperation appInterfaceUrlOperation = null;
switch (Constants.LINEFLAG) {
case 1:
appInterfaceUrlOperation = new AppInterfaceUrlOperationLine();
break;
case 2:
appInterfaceUrlOperation = new AppInterfaceUrlOperationOnLine();
break;
}
return appInterfaceUrlOperation;
}
}
5.使用工廠類(lèi)
AppInterfaceUrlOperation appInterfaceUrlOperation = new AppInterfaceUrlOperationFactory().createAppInterfaceUrlperation();
String appInterfaceUrl = appInterfaceUrlOperation.getAppInterfaceUrl();
6.Constants.java中的內(nèi)容
public static final String ONLINEURL = "http://eastelite.com.cn/webservices/";//線(xiàn)上地址
public static final String LINEURL = "http://eastelite.com.cn/webservices/";//線(xiàn)下地址
public static final int LINEFLAG = 1;//1.線(xiàn)下地址 2.線(xiàn)上地址
總結(jié):
- AppInterfaceUrlOperationFactory 工廠類(lèi)用于創(chuàng)建線(xiàn)上和線(xiàn)下接口地址類(lèi)的實(shí)例,并通過(guò)LINEFLAG標(biāo)識(shí)切換線(xiàn)上線(xiàn)下環(huán)境,若新增加其他環(huán)境,則新建一個(gè)類(lèi)并通過(guò)工廠創(chuàng)建實(shí)例即可。
- 當(dāng)我們?cè)谑褂貌煌h(huán)境接口地址的時(shí)候,有了這個(gè)工廠類(lèi),我們只需要配置Constants的LINEFLAG標(biāo)識(shí)即可,無(wú)需關(guān)注其他地方。