首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 範式工廠模式實現

     編輯:關於C++

模板工廠類設計

實現一個通用的工廠模板,支持產品註冊、註銷、創建,並可自定義錯誤處理策略。

核心代碼

#ifndef TEMPLATE_H
#define TEMPLATE_H
#include <map>

template
<
    class AbstractProduct,
    typename IdentifierType,
    class ProductCreator = AbstractProduct*(*)(),
    template <typename, class> class FactoryErrorPolicy = DefaultFactoryError
>
class Factory {
public:
    bool Register(const IdentifierType& id, ProductCreator creator) {
        return associations_.insert(AssocMap::value_type(id, creator)).second;
    }
    bool UnRegister(const IdentifierType& id) {
        return associations_.erase(id) == 1;
    }
    AbstractProduct* CreateObject(const IdentifierType& id) {
        typename AssocMap::const_iterator i = associations_.find(id);
        if (i != associations_.end()) return (i->second)();
        return OnUnknownType(id);
    }
private:
    typedef std::map<IdentifierType, ProductCreator> AssocMap;
    AssocMap associations_;
};

template <class IdentifierType, class ProductType>
class DefaultFactoryError {
public:
    class Exception : public std::exception {
    public:
        Exception(const IdentifierType& unknownId) : unknownId_(unknownId) {}
        virtual const char* what() { return "unknown object type passed to Factory"; }
        const IdentifierType GetId() { return unknownId_; }
    private:
        IdentifierType unknownId_;
    };
protected:
    static ProductType* OnUnknownType(const IdentifierType& id) {
        throw Exception(id);
    }
};
#endif
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved