通过泛型+接口实现多变的参数

1.AbsItemManager.java

package org.example.testGeneric;

import com.google.common.collect.Maps;

import java.util.Map;

public abstract class AbsItemManager {
    protected Map map = Maps.newHashMap();

    /**
     * 要做什么操作,交给子类处理
     *
     * @param e
     */
    public abstract void clear(E e);

    public void absF() {
        map.forEach((k, v) -> {
            clear(v);
        });
    }
}

2.ItemManager.java

package org.example.testGeneric;

public class ItemManager extends AbsItemManager {
    public void f() {
        ItemEntity itemEntity = map.computeIfAbsent(1, k -> new ItemEntity());

        System.out.println(itemEntity.getCount());
        absF();
        System.out.println(itemEntity.getCount());
    }

    @Override
    public void clear(ItemEntity itemEntity) {
        itemEntity.setCount(itemEntity.getCount() - 100);
    }
}

3.ItemEntity.java

package org.example.testGeneric;

import lombok.Data;

@Data
public class ItemEntity {
    private int id = 1000;
    private int count = 600;
}

4.Main.java

package org.example.testGeneric;

public class Main {
    public static void main(String[] args) {
        ItemManager itemManager = new ItemManager();
        itemManager.f();
    }
}

总结:再子类中,我们拿到的map中k,v的类型是确定的,这时我们就可以做一些事情。

你可能感兴趣的:(#,javase,java)