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