一.实例1,如下:
#include <iostream>
#include <string>
class Startable;
class StartableProcess{
public:
StartableProcess(Startable& _startable):startable(_startable){
std::cout<<"Construct StartableProcess"<<std::endl;
}
void run();
private:
Startable& startable;
};
class Startable{
public:
Startable():_process(*this){
std::cout<<"Construct Startable"<<std::endl;
}
void start(){
std::cout<<"Startable::start()"<<std::endl;
_process.run();
}
virtual void prerun(){
std::cout<<"Startable::prerun()"<<std::endl;
run();
}
virtual void run() = 0;
private:
StartableProcess_process;
};
class RTMFPServer:public Startable{
public:
RTMFPServer(){
std::cout<<"Construct RTMFPServer"<<std::endl;
}
void start(){
std::cout<<"RTMFPServer::start()"<<std::endl;
Startable::start();
}
void run(){
std::cout<<"RTMFPServer::run()"<<std::endl;
handle();
}
virtual void handle();
};
class Server:public RTMFPServer{
public:
void handle(){
std::cout<<"Server::handle()"<<std::endl;
}
};
inline void Startable::run(){
std::cout<<"Startable::run()"<<std::endl;
prerun();
}
inline void StartableProcess::run(){
std::cout<<"StartableProcess::run()"<<std::endl;
startable.prerun();
}
inline void RTMFPServer::handle(){
std::cout<<"RTMFPServer::handle()"<<std::endl;
}
int main(int argc,char** argv){
Server server;
server.start();
return 0;
}
二.实例2,如下:
#include <iostream>
#include <string>
class RTMFPManager;
class RTMFPServer{
public:
RTMFPServer(int cores){
std::cout<<"Construct RTMFPServer,cores="<<cores<<std::endl;
}
void start(){
std::cout<<"RTMFPServer::start()"<<std::endl;
run();
}
void run();
virtual void manage(){
std::cout<<"RTMFPManager::manage()"<<std::endl;
}
};
class RTMFPManager{
public:
RTMFPManager(RTMFPServer& server):_server(server){
std::cout<<"Construct RTMFPManager"<<std::endl;
handle();
}
private:
void handle() {
std::cout<<"RTMFPManager::handle()"<<std::endl;
_server.manage();
}
RTMFPServer& _server;
};
class LinyanwenServer:public RTMFPServer{
public:
LinyanwenServer(int cores):RTMFPServer(cores){
}
virtual void manage(){
std::cout<<"LinyanwenServer::manage()"<<std::endl;
}
};
void RTMFPServer::run(){
std::cout<<"RTMFPServer::run()"<<std::endl;
RTMFPManager manager(*this);
}
int main()
{
int core = 99;
LinyanwenServer server(core);
server.start();
return 0;
}
转载请注明出处:山水间博客,http://blog.csdn.net/linyanwen99/article/details/8567685