1、定义两种不同分配内存创建对象的策略

template<classT>

classOpNewCreator

{

public:

        staticT*create()

        {

                  std::cout<< "OpNewCreator"<< std::endl;

                  returnnewT;

        }

protected:

        ~OpNewCreator(){}

};

 

template<classT>

classMallocCreator

{

public:

        staticT*create()

        {

                  std::cout<< "MallocCreator"<< std::endl;

                  void *buf =malloc(sizeof(T));

                  if (!buf)

                           return 0;

                  returnnew (buf)T;

        }

protected:

        ~MallocCreator(){}

};

 

2template template定义可以根据不同型别和策略生成对象Policy

 

template<classT,template<class>classCreationPolicy>

classWidgetManager:publicCreationPolicy<T>

{

public:

   typedefCreationPolicy<T>BaseClass;

   T*create()

   {

       T* tmp=BaseClass::create();

       return tmp;

   }

};

 

3、定义两个实际的类型

classSliderWidget

{

public:

   SliderWidget()

   {

       std::cout<<"Slider Widget created"<<std::endl ;

   }

};

 

 

classBoxWidget

{

public:

   BoxWidget()

   {

       std::cout<<"Box Widget created"<<std::endl;

   }

};

 

4、使用示例

typedefWidgetManager<BoxWidget,OpNewCreator>BoxWidgetManager;

typedefWidgetManager<SliderWidget,MallocCreator>SliderWidgetManager;

 

intmain()

{

   BoxWidgetManager boxWidgetManager;

  BoxWidget* boxWidet=boxWidgetManager.create();

   SliderWidgetManager silderWidgetManager;

   SliderWidget* silderWidet =silderWidgetManager.create();

   pause();

}

 Policy以不同策略不同型别生产对象

相关文章:

  • 2021-12-12
  • 2022-01-21
  • 2021-08-12
  • 2022-12-23
  • 2021-11-29
  • 2021-07-14
  • 2021-10-04
  • 2022-01-21
猜你喜欢
  • 2021-10-26
  • 2022-12-23
  • 2021-08-17
  • 2021-12-15
  • 2021-10-06
  • 2021-07-01
  • 2021-11-12
相关资源
相似解决方案