6

私は次の (簡略化された) ファクトリ デザインを使用して、いくつかの継承階層のオブジェクトを作成していますが、特別なものではありません。

// class to create
class Class
{
public:
  Class(Type type, Foo foo);
};

// Simple creator class.
// Used in practice to do some runtime checks about whether or not construction is allowed.
class Creator
{
public:
  Class* create( Type type, Foo foo ) const
  {
    return new Class( type, foo );
  }
};

class Factory
{
public:
  Factory
  {
    // fill object creator map on construction
    _map[ "name" ] = new Creator<Class>;
  }

  Class* create( const std::string& name, Type type, Foo foo )
  {
    // fowards to map entry
    return _map[name]->create( type, foo );
  }

private:
 std::map<std::string, Creator*> _map;
}

// client code
int main()
{
  Factory f;
  factory.create(name, type, foo);
}

ファクトリが継承階層全体に固定の署名を課すため、別のコンストラクター署名を持つサブクラスを作成したい場合、問題が発生します。つまり、次のクラスでは、階層の他のすべてのクラスにこの拡張シグネチャを再度課すことなく、ファクトリ構築を介して新しい 3 番目のパラメーターを指定する方法がありません。

class ExtClass : public Class
{
public:
  Class(Type type, Foo foo, NewMember nm)
    : Class(type, foo),
      _nm(nm)

private:
  NewMember _nm;
};

主な変更を加えずに、現在の設計でこれを機能させる方法はありますか? テンプレートまたはバインド オブジェクトを使用して、さまざまな引数の呼び出しを可能にすることを考えています。それとも、この場合、工場設計とは異なる解決策を提案しますか?

4

2 に答える 2

1

この回答は、私の最初の解決策とは十分に異なり、別の回答にした「主要な変更」と見なされる可能性のあるものが含まれています。

私の意見では、以前のソリューションよりも優れていますが、正確な要件が何であるかによって異なります。ここでの機能は次のとおりです。

  • 作成者 ID は一意です。
  • CreateObjectパラメータの暗黙的な変換をサポートします。

const&コンストラクターがパラメーターを取らなければならないという同じ制限が存在します。問題ではないかもしれませんが、このソリューションには C++11 のみが必要です。もちろん、新しい C++17 のタプル機能を使えば、もう少し簡単になります。

#include <boost/functional/factory.hpp>
#include <boost/function.hpp>
#include <boost/variant.hpp>

#include <map>
#include <stdexcept>
#include <tuple>
#include <type_traits>
#include <utility>
// Just for debugging.
#include <iostream>
#include <typeinfo>
#include <cxxabi.h>

// Tuple manipulation.

template <typename Signature>
struct signature_impl;

template <typename ReturnType, typename... Args>
struct signature_impl<ReturnType(Args...)>
{
    using return_type = ReturnType;
    using param_types = std::tuple<Args...>;
};

template <typename T>
using signature_t = signature_impl<T>;


template <std::size_t... Ints>
struct indices {};

template <std::size_t N, std::size_t... Ints>
struct build_indices : build_indices<N-1, N-1, Ints...> {};

template <std::size_t... Ints>
struct build_indices<0, Ints...> : indices<Ints...> {};

template <typename Tuple>
using make_tuple_indices = build_indices<std::tuple_size<typename std::remove_reference<Tuple>::type>::value>;

// The multiple-signature factory.
template <class AbstractProduct, typename IdentifierType, typename... ProductCreators>
class multifactory
{
    using functions = boost::variant<boost::function<ProductCreators>...>;

    std::map<IdentifierType, functions> associations_;

    template <typename Signature>
    struct dispatch_foo
    {
        template <typename CreateArgs, std::size_t... Indices>
        typename std::enable_if<std::is_convertible<CreateArgs, typename signature_t<Signature>::param_types>::value, AbstractProduct>::type
        static apply(boost::function<Signature> const &f, CreateArgs && t, indices<Indices...>)
        {
            return f(std::get<Indices>(std::forward<CreateArgs>(t))...);
        }

        template <typename CreateArgs, std::size_t... Indices>
        typename std::enable_if<!std::is_convertible<CreateArgs, typename signature_t<Signature>::param_types>::value, AbstractProduct>::type
        static apply(boost::function<Signature> const &, CreateArgs &&, indices<Indices...>)
        {
            return nullptr;
        }
    };

    template <typename... CreateArguments>
    struct dispatcher : boost::static_visitor<AbstractProduct>
    {
        std::tuple<CreateArguments...> args;

        dispatcher(CreateArguments const&... args) : args{std::forward_as_tuple(args...)} {}

        template <typename Signature>
        AbstractProduct operator()(boost::function<Signature> const &f) const
        {
            int status;
            std::cout << "visitor: " << abi::__cxa_demangle(typeid(Signature).name(), nullptr, 0, &status) << "\n";
            return dispatch_foo<Signature>::apply(f, args, make_tuple_indices<std::tuple<CreateArguments...>>{});
        }
    };

public:
    template <typename ProductCreator>
    bool Register(IdentifierType id, ProductCreator &&creator) {
        return associations_.emplace(id, std::forward<ProductCreator>(creator)).second;
    }

    bool Unregister(const IdentifierType& id) {
        return associations_.erase(id) == 1;
    }

    template <typename... Arguments>
    AbstractProduct CreateObject(const IdentifierType& id, Arguments const& ... args) {
        auto i = associations_.find(id);
        if (i != associations_.end()) {
            dispatcher<Arguments...> impl(args...);
            return boost::apply_visitor(impl, i->second);
        }
        throw std::runtime_error("Creator not found.");
    }
};


struct Arity {
    virtual ~Arity() = default;
};

struct Nullary : Arity {};

struct Unary : Arity {
    Unary() {} // Also has nullary ctor.
    Unary(int) {}
};


int main(void)
{
    multifactory<Arity*, int, Arity*(), Arity*(const int&)> factory;
    factory.Register(0, boost::function<Arity*()>( boost::factory<Nullary*>() ));
    factory.Register(1, boost::function<Arity*(const int&)>(boost::factory<Unary*>()) );
    auto a = factory.CreateObject(0);
    assert(a);
    assert(typeid(*a) == typeid(Nullary));
    auto b = factory.CreateObject(1, 2);
    assert(b);
    assert(typeid(*b) == typeid(Unary));
}
于 2018-03-11T08:12:08.767 に答える