Android深入(三)-设计模式之简单工厂模式

时间:2022-06-09
本文章向大家介绍Android深入(三)-设计模式之简单工厂模式,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

概念:简单工厂模式通俗的讲就是一个类的工厂,用于生产类,而这个工厂本身就是一个类,他可以创建多个类的实例。

下面我们就来实现一个简单工厂模式。

场景:Android开发中,我们必然会调用接口,而接口地址要做测试环境和正式环境的切换,甚至需要在多个测试环境和多个正式环境中,那么接口地址就有多个。 普通的做法:直接将接口地址放在静态常量中保存,通过注释来切换接口地址或通过标识来判断环境选择正确的地址。 实践:通过简单工厂模式来完成配置。

1. 创建app接口地址基础类
package net.yibee.instantMessage;

/**
 * 基本功能:app 接口地址基础类
 * Created by wangjie on 2017/4/14.
 */
public class AppInterfaceUrlOperation {
    public String getAppInterfaceUrl() {
        return "";
    }
}
2.创建测试环境接口地址管理类
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;
    }
}
3.创建线下接口地址管理类
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;
    }
}
4.创建工厂类
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中的内容
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.线上地址
总结:
  1. AppInterfaceUrlOperationFactory 工厂类用于创建线上和线下接口地址类的实例,并通过LINEFLAG标识切换线上线下环境,若新增加其他环境,则新建一个类并通过工厂创建实例即可。
  2. 当我们在使用不同环境接口地址的时候,有了这个工厂类,我们只需要配置Constants的LINEFLAG标识即可,无需关注其他地方。