Chinaunix首页 | 论坛 | 博客
  • 博客访问: 92427687
  • 博文数量: 19283
  • 博客积分: 9968
  • 博客等级: 上将
  • 技术积分: 196062
  • 用 户 组: 普通用户
  • 注册时间: 2007-02-07 14:28
文章分类

全部博文(19283)

文章存档

2011年(1)

2009年(125)

2008年(19094)

2007年(63)

分类: C/C++

2008-04-15 21:29:45

     来源:赛迪论坛    作者:sixth

假设我们要写一个应用程序,它可以把消息传送到几个不同的公司去。消息既可以以加密方式也可以以明文(不加密)的方式传送。如果我们有足够的信息在编译期间确定哪个消息将要发送给哪个公司,我们就可以用一个 template-based(模板基)来解决问题:

class CompanyA {
public:
 ...
 void sendCleartext(const std::string& msg);
 void sendEncrypted(const std::string& msg);
 ...
};

class CompanyB {
public:
 ...
 void sendCleartext(const std::string& msg);
 void sendEncrypted(const std::string& msg);
 ...
};
... // classes for other companies

class MsgInfo { ... }; // class for holding information
// used to create a message
template
class MsgSender {
public:
 ... // ctors, dtor, etc.

 void sendClear(const MsgInfo& info)
 {
  std::string msg;
  create msg from info;

  Company c;
  c.sendCleartext(msg);
 }
 void sendSecret(const MsgInfo& info) // similar to sendClear, except
 { ... } // calls c.sendEncrypted
};

  这个能够很好地工作,但是假设我们有时需要在每次发送消息的时候把一些信息记录到日志中。通过一个 derived class(派生类)可以很简单地增加这个功能,下面这个似乎是一个合理的方法:

template
class LoggingMsgSender: public MsgSender {
public:
 ... // ctors, dtor, etc.
 void sendClearMsg(const MsgInfo& info)
 {
  write "before sending" info to the log;
  sendClear(info); // call base class function;
  // this code will not compile!
  write "after sending" info to the log;
 }
 ...
};

阅读(283) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~