Unity 背包道具搜索(2)

上一篇: http://www.cnblogs.com/plateFace/p/6490577.html

上次编写代码只是把逻辑编写出来, 对于里面的代码还存在一下问题

1. 搜索功能没有解耦

2. 添加新的搜索,只能修改源代码

3. 消除大量switch

搜索器:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SearchCollection<T>
{
    private Dictionary<int, ItemFun<T>> mExpressionDic = new Dictionary<int, ItemFun<T>>();


    public void Init()
    {
        mExpressionDic.Clear();
    }

    public void AddFilter(int id, ItemFun<T> fun)
    {
        mExpressionDic.Add(id, fun);
    }

    public List<T> Get(Dictionary<int, object> condition, IEnumerable<T> itemCollection)
    {
        List<T> tempList = new List<T>();
        ItemFun<T> func = null;
        bool isNotThrough = false;
        foreach (var item in itemCollection)
        {
            isNotThrough = true;
            foreach (var cond in condition)
            {
                func = mExpressionDic[cond.Key];

                if (func.IsSuit(item, cond.Value) == false)
                {
                    isNotThrough = false;
                    break;
                }
            }
            if (isNotThrough)
            {
                tempList.Add(item);
            }
        }
        return tempList;
    }
}
public abstract class ItemFun<T>
{
    public abstract bool IsSuit(T item, object args);
}
posted @ 2018-03-20 12:40  盘子脸  阅读(...)  评论(... 编辑 收藏