#include <memory>
class Base;
using BaseSp = std::shared_ptr<Base>;
class Base
{
public:
explicit Base(int id) : ID(id) {}
int ID;
};
class Sorter
{
public:
virtual bool sort(const BaseSp &l, const BaseSp &r) { return true; }
};
using SorterSp = std::shared_ptr<Sorter>;
class BaseNameSorter : public Sorter
{
public:
bool sort(const BaseSp &l, const BaseSp &r) override { return l->ID < r->ID; }
};
using BaseNameSorterSp = std::shared_ptr<BaseNameSorter>;
class BaseDateSorter : public Sorter
{
public:
bool sort(const BaseSp &l, const BaseSp &r) override { return l->ID < r->ID; }
};
using BaseDateSorterSp = std::shared_ptr<BaseDateSorter>;
class ShareSorter
{
public:
SorterSp sorter;
};
using ShareSorterSp = std::shared_ptr<ShareSorter>;
using ShareSorterWp = std::weak_ptr<ShareSorter>;
class SortBase
{
public:
explicit SortBase(BaseSp data, ShareSorterSp sorter) : base(data), m_sortDelegate(sorter) {}
bool operator<(const SortBase &other) const
{
bool isExpired = m_sortDelegate.expired();
auto delegate = m_sortDelegate.lock();
if (isExpired || !delegate || !delegate->sorter) {
assert(false);
return true;
}
return delegate->sorter->sort(base, other.base);
}
BaseSp base;
ShareSorterWp m_sortDelegate;
};
class Group
{
public:
std::set<SortBase> m_set;
ShareSorterSp m_sorter;
};
int main()
{
Group styleGroups; //数组组
ShareSorterSp shareSorter = std::make_shared<ShareSorter>();
shareSorter->sorter = std::make_shared<BaseNameSorter>();
styleGroups.m_sorter = shareSorter; //初始化组与子共享排序器
BaseSp base1 = std::make_shared<Base>(0);
BaseSp base2 = std::make_shared<Base>(1);
styleGroups.m_set.emplace(base1, styleGroups.m_sorter); //添加待排序数据
styleGroups.m_set.emplace(base2, styleGroups.m_sorter); //触发共享排序器
shareSorter->sorter = std::make_shared<BaseDateSorter>();
BaseSp base3 = std::make_shared<Base>(2); //换排序方式
styleGroups.m_set.emplace(base3, styleGroups.m_sorter);
return 0;
}