概念:简单工厂模式通俗的讲就是一个类的工厂,用于生产类,而这个工厂本身就是一个类,他可以创建多个类的实例。
下面我们就来实现一个简单工厂模式。
场景:Android开发中,我们必然会调用接口,而接口地址要做测试环境和正式环境的切换,甚至需要在多个测试环境和多个正式环境中,那么接口地址就有多个。 普通的做法:直接将接口地址放在静态常量中保存,通过注释来切换接口地址或通过标识来判断环境选择正确的地址。 实践:通过简单工厂模式来完成配置。
package net.yibee.instantMessage;
/**
* 基本功能:app 接口地址基础类
* Created by wangjie on 2017/4/14.
*/
public class AppInterfaceUrlOperation {
public String getAppInterfaceUrl() {
return "";
}
}
package net.yibee.instantMessage;
import net.yibee.utils.Constants;
/**
* 基本功能:线上环境
* Created by wangjie on 2017/4/14.
*/
public class AppInterfaceUrlOperationOnLine extends AppInterfaceUrlOperation{
@Override
public String getAppInterfaceUrl() {
return Constants.ONLINEURL;
}
}
package net.yibee.instantMessage;
import net.yibee.utils.Constants;
/**
* 基本功能:线下环境
* Created by wangjie on 2017/4/14.
*/
public class AppInterfaceUrlOperationLine extends AppInterfaceUrlOperation {
@Override
public String getAppInterfaceUrl() {
return Constants.LINEURL;
}
}
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;
}
}
AppInterfaceUrlOperation appInterfaceUrlOperation = new AppInterfaceUrlOperationFactory().createAppInterfaceUrlperation();
String appInterfaceUrl = appInterfaceUrlOperation.getAppInterfaceUrl();
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.线上地址