0
点赞
收藏
分享

微信扫一扫

java规范(一)------方法设计---返回多参数的方法怎么封装

腾讯优测 2023-08-08 阅读 52



两个方法

一是新建对象包含多参数

二是用map封装


把多参数新建为对象符合面向对象编程的思维,也可以使代码整洁。

使用map则是方便,不需要新建对象。

两种方法视情况使用。



假如我们有2个变量count和content需要经过一个方法里改变它的值我们可以用下面的方法:


main{
int count=0;
String content=“”;
changeValue(count,content);
 System.out.println(count);
 System.out.println(content);
}

private void changeValue(int count,String content){
  count++;
content="new content";
 }





但是这种写法很不友好, 我们最好不用返回值当作参数。因为这样变量的作用域不明显,而且容易混乱。


最好是 每个方法返回我们需要改成的值。


但是如果涉及到多参数参与变化的方法时怎么办呢?


可以使用map来进行封装再一起返回:

main{

  Map<String, Object> data =changeValue(count,content);
 System.out.println(data.get("count"));
 System.out.println(data.get("content"));
}

private Map<String, Object> changeValue(int count,String content){
       return MapBuilder
                .forType(String.class, Object.class)
                .with("count", count++)                
                .with("content", "new content")
                .build();
 }






package com.test.util;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Map构造器
 * 
 * 
 */
public final class MapBuilder<K, V> {
    private Map<K, V> map;

    private MapBuilder() {
        map = new HashMap<K, V>();
    }

    /**
     * create a builder
     * 
     * @return
     */
    public static <K, V> MapBuilder<K, V> create() {
        return new MapBuilder<K, V>();
    }

    /**
     * create a builder
     * 
     * @param kClass key type
     * @param vClass value type
     */
    public static <K, V> MapBuilder<K, V> forType(Class<K> kClass, Class<V> vClass) {
        return new MapBuilder<K, V>();
    }

    /**
     * create a builder and put a kv pair.
     * 
     * @param key
     * @param value
     * @return
     */
    public static <K, V> MapBuilder<K, V> createWith(K key, V value) {
        return new MapBuilder<K, V>().with(key, value);
    }

    /**
     * put 键值对
     * 
     * @param key 键
     * @param value 值
     * @return
     */
    public MapBuilder<K, V> with(K key, V value) {
        map.put(key, value);
        return this;
    }

    /**
     * 方法名称意义不明,放弃使用<br>
     * 兼容过时代码,暂不删除。
     * 
     * @param key
     * @param value
     * @return
     */
    @Deprecated
    public static <K, V> MapBuilder<K, V> makeNew(K key, V value) {
        return createWith(key, value);
    }

    /**
     * put 键值对 {@link #with(Object, Object)}
     * 
     * @param key 键
     * @param value 值
     * @return
     */
    @Deprecated
    public MapBuilder<K, V> make(K key, V value) {
        return with(key, value);
    }

    /**
     * 构造Map对象
     * 
     * @return 不可再修改的map
     */
    public Map<K, V> build() {
        return Collections.unmodifiableMap(map);
    }

    /**
     * 返回原生Map对象
     * 
     * @return
     */
    public Map<K, V> original() {
        return map;
    }

}





举报

相关推荐

0 条评论