享元模式实践

前言

享元模式的核心在于需要定义一个池容器。对象生成后必须有一个唯一的标识供访问者从容器中获取,因此 Map 常被作为容器对象出现。池容器中的对象生命周期由池容器决定,访问者无法干涉。

实践案例

1 享元模式实践一

模拟数据库连接初始化、调用和释放。

1.1 享元工厂

public class ConnectionPoolTool {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    //连接池
    private Vector<Connection> connectionPool;
    //url
    private static final String url = "jdbc:mysql://127.0.0.1:3306/loan";
    //用户名
    private static final String userName = "******";
    //密码
    private static final String password = "******";
    //启动类,就是一个类,通常是写死的
    private static final String driverClassName = "com.mysql.jdbc.Driver";
    //初始连接池大小
    private static final int poolSize = 100;

    //享元模式应用
    public ConnectionPoolTool(){
        connectionPool = new Vector<>(poolSize);
        //初始化数据库连接
        for(int index=0; index<poolSize; index++){
            try {
                //创建数据库连接
                Class.forName(driverClassName);
                Connection connection = DriverManager.getConnection(url, userName, password);
                //存入集合中
                connectionPool.add(connection);
            } catch (Exception e) {
                this.logger.error("Exception ", e);
            }
        }
    }

    /**
     * 描述:获取连接
     */
    public synchronized Connection getConnection(){
        Connection connection = null;
        if(connectionPool.size() > 0){
            //享元模式应用
            connection = connectionPool.get(0);
            connectionPool.remove(connection);
        }
        return connection;
    }

    /**
     * 描述:释放连接
     */
    public synchronized void releaseConnection(Connection connection){
        connectionPool.add(connection);
    }

1.2 客户端调用/测试

public class Client {

    public static void main(String[] args){
        ConnectionPoolTool connectionPoolTool = new ConnectionPoolTool();

        //获取连接
        Connection connection = connectionPoolTool.getConnection();
        //使用 start
        // ...
        //使用 end
        //释放连接
        connectionPoolTool.releaseConnection(connection);
    }
}

2 享元模式实践二

模拟项目中将部分实体信息中的用户编号和机构编号转换为对应的用户名称和机构名称并借助反射等方式设置到对应的字段上。

2.1 基础类

/**
 * 描述:domain 基类
 */
public class BaseDTO implements Serializable {
}

/**
 * 描述:需要转换的角色
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CustomerInfoDTO extends BaseDTO {

    private String custId; //客户编号
    private String custNm; //客户名称
    private String ctfTp; //证件类型
    private String cftNo; //证件编号
    private String approvedOrgId; //审批机构编号
    private String approvedOrgName; //审批机构名称
    private String inputOrgId; //登记机构编号
    private String inputOrgName; //登记机构名称
    private String inputDate; //登记日期
    private String updateOrgId; //更新机构编号
    private String updateOrgName; //更新机构名称
    private String updateDate; //更新日期

    //get、set方法...
}

2.2 享元角色

/**
 * 描述:机构信息(享元角色)
 */
@Data
@NoArgsConstructor
public class OrgInfo {

    //机构编号
    private String orgId;
    //机构名称
    private String orgName;
    //机构层级
    private String orgLevel;
    //上级机构
    private String parentId;

    //get、set 方法...
}

2.3 享元工厂

public class TransformUtil <T extends BaseDTO> {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    //存储已查询过的机构信息,享元模式应用
    private final static Map<String, OrgInfo> orgCache = new HashMap<String, OrgInfo>(16);

    //转义:id -> name
    public void transformIdToName(T t, String... fieldArray) {
        Class<T> clazz = (Class<T>) t.getClass();

        //定义变量:对象 t 的 set 和 get 方法
        Method setMethod = null, getMethod = null;
        //定义变量:对象 t 中对应字段的名称和编号
        String nameValue = "", idValue = "";

        for(String field : fieldArray){
            //编号字段名称,名称字段名称
            String idFieldName = field + "Id", nameFieldName = field + "Name";

            //拼接 get 方法
            String getMethodName = "get" + idFieldName.substring(0, 1).toUpperCase() + idFieldName.substring(1);

            //获取对象中指定字段的值
            try {
                getMethod = clazz.getMethod(getMethodName);
                if(getMethod != null){
                    idValue = (String) getMethod.invoke(t);
                }
            } catch (NoSuchMethodException e) {
                this.logger.error("对象/类{}不存在{}方法", clazz.getName(), getMethodName);
            }catch (Exception e){
                this.logger.error("获取对象中指定字段值异常", e);
            }

            if(StringUtils.isNotBlank(idValue)){
                if(orgCache.containsKey(idValue)){
                    //享元模式应用
                    nameValue = orgCache.get(idValue).getOrgName();
                }else{
                    //定义变量:机构对象,默认为null
                    OrgInfo orgInfo = null;
                    //查询机构信息逻辑 start
                    //orgInfo = 根据id查询机构信息方法
                    //查询机构信息逻辑 start

                    if(orgInfo != null){ //若未查询到对应的机构信息,则默认为:""
                        //查询出机构信息后放入内存
                        orgCache.put(idValue, orgInfo);
                        //机构名称
                        nameValue = orgInfo.getOrgName();
                    }
                }
            }

            //拼接 set 方法
            String setMethodName = "set" + nameFieldName.substring(0, 1).toUpperCase() + nameFieldName.substring(1);
            //设置对象中指定字段的值
            try {
                setMethod = clazz.getMethod(setMethodName, String.class);
                if(setMethod != null){
                    setMethod.invoke(t, nameValue);
                }
            } catch (NoSuchMethodException e) {
                this.logger.error("对象/类{}不存在{}方法", clazz.getName(), setMethodName);
            } catch (Exception e){
                this.logger.error("设置对象中指定字段值异常", e);
            }
        }
    }
}

2.4 客户端调用/测试

public class Client {
    private static Logger logger = LoggerFactory.getLogger(Client.class);

    public static void main(String[] args){
        TransformUtil<CustomerInfoDTO> transformUtil = new TransformUtil<CustomerInfoDTO>();

        CustomerInfoDTO customerInfo = new CustomerInfoDTO();
        customerInfo.setApprovedOrgId("1100");
        customerInfo.setInputOrgId("1101");
        customerInfo.setUpdateOrgId("1100");

        transformUtil.transformIdToName(customerInfo, "approvedOrg", "inputOrg", "updateOrg");
        logger.info("转义后对象信息:{}", customerInfo);
        //测试结果:
        //18:13:58.350 [main] INFO com.design.service.impl.share.Client - 转义后对象信息:CustomerInfoDTO(custId=null, 
        //custNm=null, ctfTp=null, cftNo=null, approvedOrgId=1100, approvedOrgName=Ali, inputOrgId=1101, inputOrgName=JD, 
        // inputDate=null, updateOrgId=1100, updateOrgName=Ali, updateDate=null)
    }
}

注意事项

  1. 项目中需要提前引入数据库连接驱动(本案例中是 mysql 连接驱动)和 lombok 的jar包。依赖如下:
	<dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>3.1.12</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.18</version>
    </dependency>
  1. 开发工具中需安装 lombok 插件。安装步骤(IDEA):File -> Settings… -> Plugins -> Marketplace -> 搜索 lombok -> Install -> Restart 开发工具。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值