基于原则设计

✍ dations ◷ 2025-11-16 09:01:29 #计算机编程,C++

基于原则设计(Policy-Based Class Design)又名policy-based class design 或 policy-based programming, 是一种基于C++计算机程序设计规范,以原则(Policy)为基础,并结合C++的模板超编程(template metaprogramming)。policy-based首见于 Andrei Alexandrescu 出版的 《Modern C++ Design》 一书以及他在C/C++ Users Journal杂志专栏 Generic<Programming> 。

Policy的意思是方针,或策略,也就是将原本复杂的系统,拆解成多个独立运作的“策略类别”(policy class),每一组policy class都只负责单纯如行为(behavior, method)或结构(structure)的某一方面。Templetes与多重继承(Multiple Inheritance)两项技术互补。多重继承由于继承自多组 Base Class,故缺乏型别消息(type information),而Templetes基于型别,拥有丰富的型别消息。多重继承容易扩张,而Templetes的特化(Specialization)不容易扩张。Policy-Based Class Design 同时使用了 Template 以及 Multiple Inheritance 两项技术,结合两者的优点。

template<         class Policy1,         class Policy2,         class Policy3>class PolicyBasedClass:public Policy1, public Policy2{public:   PolicyBasedClass(){};};

PolicyBasedClass则称为宿主类别(host class),只需要切换不同 Policy Class,就可以得到不同的需求。Policy不一定要被宿主(host)继承,只需要用委托(delegation)完成这一工作。但policies必须遵守一个隐含的constraint,接口(interface)必须一样,故参数不能有巨大改变。

Policy class有点类似回调函数(callbacks),但不同的是,callback只是一个函数,至于 policy class 则尽可能包含许多的 functions (methods), 有时还会结合状态变量(state variables)与其他各式各样的类型,如嵌套类型(nested types)。

policy 的一个重要的特征是,宿主类别(host class)经常(并不一定要)使用多重继承的机制去使用多个 policy classes. 因此在进行 policy 拆解时,必须要尽可能达成正交分解(Orthogonal Decomposition),policy彼此独立运作,不相互影响。

在 C++ 的Policy-Based Design 中,用来建构 Template 的类别参数(也就是policy class),本身亦可以是一个 Tempate 化的类别,形成所谓的 Template Template Parameter。

如果 Read()、Write() 有各种不同名目的参数时,可以利用 template 的不完全具现化 (Incomplement Instantiation) 特征检实现各个参数不同的成员函数(member function)。在host class中,可以撰写不同参数版本的 Read(...) 函数,这有赖于c++ compiler的协助。

template<	class T,	template< class > class ReadPolicy,	template< class > class WritePolicy>class ResourceManager	:	public ReadingPolicy< T >,	public WritingPolicy< T >{public:   void Read();   void Write(XmlElement*);   void Write(DataSource*);};

上述的class T即是一个Template Template Parameter,这使得 Policy Class 更具扩展性与弹性,能够处理各种类型的实体(instance)。

void main(){  ResourceManager< AnimationEntity, BinaryReader, BinaryWriter > ResMgr1;  ResourceManager< ScriptEntity, TextReader, TextWriter > ResMgr2;}

示例

下例是 C++ hello world的示例,可以使用各种原则(policies)打印文字。

template<    typename output_policy,    typename language_policy>class HelloWorld  : public output_policy,    public language_policy{    using output_policy::Print;    using language_policy::Message;public:    //behaviour method    void Run()    {        //two policy methods        Print( Message() );    }};#include <iostream>class HelloWorld_OutputPolicy_WriteToCout{protected:    template< typename message_type >    void Print( message_type message )    {        std::cout << message << std::endl;    }};#include <string>class HelloWorld_LanguagePolicy_English{protected:    std::string Message()    {        return "Hello, World!";    }};class HelloWorld_LanguagePolicy_German{protected:    std::string Message()    {        return "Hallo Welt!";    }};int main(){/* example 1 */    typedef        HelloWorld<            HelloWorld_OutputPolicy_WriteToCout,            HelloWorld_LanguagePolicy_English        >            my_hello_world_type;    my_hello_world_type hello_world;    hello_world.Run(); //returns Hello World!/* example 2  * does the same but uses another policy, the language has changed */    typedef        HelloWorld<            HelloWorld_OutputPolicy_WriteToCout,            HelloWorld_LanguagePolicy_German        >            my_other_hello_world_type;    my_other_hello_world_type hello_world2;    hello_world2.Run(); //returns Hallo Welt!}

你可以更容易的撰写其他的 Output policy, 单靠你创造更新的Policy class并实现print于其中。

相关

  • 日冕日冕是环绕太阳周围的等离子体光环, 环绕其它恒星的称为冕或星冕。太阳的日冕延伸到外太空数百万公里,在每一次的日全食中都很容易看到;平常也可以透过日冕仪观测。英文的冕 (co
  • 帕特里克·斯特普托帕特里克·克里斯托弗·斯特普托(英语:Patrick Christopher Steptoe,1913年6月9日-1988年3月21日),英国医生,体外人工受精技术的先驱之一。曾是罗伯特·G·爱德华兹的亲密合作者,二
  • 欧盟卫星中心坐标:40°29′22″N 3°26′19″W / 40.489525°N 3.438630°W / 40.489525; -3.438630欧盟卫星中心(European Union Satellite Centre,EUSC)是欧盟的欧盟理事会辖下机构,负责透
  • 灯心草灯心草(学名:),又名圆蔺、灯芯草、水灯花、水灯心、蔺草、灯草、龙须草、野席草、马棕根、野马棕,是灯心草属多年生草本植物,分布于全球温暖地区,生长于海拔200-3,400米的地区。杆丛
  • 波城波城(法语:Pau,法语发音:.mw-parser-output .IPA{font-family:"Charis SIL","Doulos SIL","Linux Libertine","Segoe UI","Lucida Sans Unicode","Code2000","Gentium","Gentium
  • 桂阳县第一中学坐标:25°45′00″N 112°43′32″E / 25.750116°N 112.725649°E / 25.750116; 112.725649桂阳县第一中学(英语:No.1 Meddle School Guiyang County)位于湖南省郴州市桂阳县关
  • 煌斑岩煌斑岩为一种浅成岩,通常颜色较深,含有由暗色矿物组成的斑晶,在肉眼观察时,其标本闪闪发光,因此而得名。其组成成分多为长石和与斑晶相同的暗色矿物,尤其是云母。按其成分可分为:
  • 丹·福格勒丹尼尔·凯文·“丹”·福格勒(英语:Daniel Kevin "Dan" Fogler,1976年10月20日-)是一名美国男演员、独角喜剧演员、剧作家、导演和音乐家。曾赢得一座东尼奖和戏剧世界奖(英语:The
  • 计六奇计六奇(1622年-?),字用宾,号天节子,别号九峰居士。江南无锡兴道乡(今前洲、玉祁街道)人。明末清初史学家。家境清贫,二次乡试不中,康熙二年(1663年)后以教学为业,并开始撰写《明季北略》和
  • 霍华德·齐默尔曼霍华德·艾略特·齐默尔曼(英语:Howard Elliot Zimmerman,1926年7月5日-2012年2月12日),化学家,威斯康星大学麦迪逊分校化学教授。他于1980年入选为美国国家科学院院士,并于1986年荣