Policy-based design

       One problem which often arises during programming is how to build a base set of functionality which can be extended by the user, while still being modular enough to make it easy to replace only certain parts of an implementation without having to resort to copy & paste techniques. I guess everybody of us has faced this problem at least once, and came up with different solutions. There is a powerful and elegant technique called policy-based design for solving this kind of problem.

      Simple example

#include<iostream>
#include<string>
using namespace std;

template<typename output_policy,typename language_policy>
class HelloWorld:public output_policy,public language_policy
{
    using output_policy::Print;
    using language_policy::Message;

public:
    void Run()
	{
		Print(Message());
    }
};

class HelloWorld_OutputPolicy_WriteToCout
{
protected:
	template<typename message_type>
    void Print(message_type message)
    {
		std::cout << message << std::endl;
    }
};

class HelloWorld_LangguagePolicy_English
{
protected:
	std::string Message()
    {
        return "Hello World!";
    }
};

class HelloWorld_LanguagePolicy_German
{
protected:
	std::string Message()
    {
        return "Hello Policy!";
    }
};

int main()
{
    typedef HelloWorld<HelloWorld_OutputPolicy_WriteToCout,HelloWorld_LangguagePolicy_English> myPolicyClass;
    myPolicyClass hello1;
    hello1.Run();

    typedef HelloWorld<HelloWorld_OutputPolicy_WriteToCout,HelloWorld_LanguagePolicy_German> myOtherPolicyClass;
    myOtherPolicyClass hello2;
    hello2.Run();
}

      Makefile

all:policy

# which compiler
CC=g++ 
# Where are include file kept
INCLUDE = .

# Where to install
INSTDIR = /usr/local/bin

# Options for development
CFLAGS = -g -Wall -ansi

policy:policy.o
	$(CC) -o policy policy.o

policy.o:policy.cpp
#	$(CC) -I$(INCLUDE) $(CFLAGS) -c msgqueue.c
#	$(CC) -D_REENTRANT -c msgqueue.c -lpthread
	$(CC) -c policy.cpp -o policy.o

clean:
	-rm  policy.o policy

install:policy
	@if [-d $(INSTDIR) ];\
        then \
        cp policy $(INSTDIR);\
        chmod a+x $(INSTDIR)/policy;\
        chmod og-w $(INSTDIR)/policy;\
        echo "Install in $(INSTDIR)";\
    else \
       echo "Sorry,$(INSTDIR) does not exist";\
    fi 

      Runing result:

       Hello World

       Hello Policy

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值