关闭

回调框架 不知道异步可以用不,在尝试

231人阅读 评论(0) 收藏 举报
#include <iostream>
using namespace std;

class ITransaction
{
public:
	virtual ~ITransaction(){}
};
class Task
{
public:
	virtual int process(ITransaction *) = 0;
	virtual void doAfterSync(ITransaction *ctx)
	{

	}
	void setCompleteListener(Task *l)
	{
		mListener = l;
	}
	void complited(ITransaction *ctx)
	{
		std::cout << "complited..." << std::endl;
		if (mListener) {
			mListener->doAfterSync(ctx);
		} else {
			std::cout << "mListener is null" << std::endl;
		}
	}
private:
	Task *mListener;
};

enum {
	START = 0,
	A_START,
	A_COMPLETE,
	B_START,
	B_COMPLETE
};

std::string strStatus[] = {"start", "a_start", "a_complete", "b_start", "b_complete"};
class Transaction : public ITransaction
{
public:
	Transaction():status(START){}
	int status;
};

class TaskA : public Task
{
public:
	TaskA()
	{
	}

	void setBTask(Task *taskB)
	{
		taskB_ = taskB;
	}
	int process(ITransaction *ctx)
	{
		ctx_ = dynamic_cast<Transaction *>(ctx);
		std::cout << "TaskA is running..., status is " << strStatus[ctx_->status] << std::endl;
		switch (ctx_->status)
		{
			case START:
				ctx_->status = A_START;
				std::cout << "status is " << strStatus[ctx_->status] << std::endl;

				taskB_->setCompleteListener(this);
				taskB_->process(ctx_);
				return 1; // not finished
			case B_COMPLETE:
				complited(ctx_);
				return 0;
		}
	}
	void doAfterSync(ITransaction *ctx)
	{
		std::cout << "TaskA::doAfterSync"<< std::endl;
		if (ctx_->status == B_COMPLETE) {
			process(ctx);
		}
	}
private:
	Task *taskB_;
	Transaction *ctx_;
};

class TaskB : public Task
{
public:
	int process(ITransaction *ctx)
	{
		std::cout << "TaskB is running..." << std::endl;
		ctx_ = dynamic_cast<Transaction *>(ctx);
		ctx_->status = B_COMPLETE;
		std::cout << "status is " << strStatus[ctx_->status] << std::endl;
		complited(ctx_);
		return 0;
	}
private:
	Transaction *ctx_;
};

class Controller
{
public:
	Controller(TaskA *taskA, TaskB *taskB) : taskA_(taskA), taskB_(taskB)
	{
	}
	void do_process(Transaction *ctx_)
	{
		taskA_->process(ctx_);
	}

	TaskA *taskA_;
	TaskB *taskB_;
};

int main()
{
	Transaction *ctx = new Transaction;

	TaskA *taskA = new TaskA();
	TaskB *taskB = new TaskB();
	taskA->setBTask(taskB);

	Controller *ctl = new Controller(taskA, taskB);
	ctl->do_process(ctx);
	return 0;
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:5995次
    • 积分:300
    • 等级:
    • 排名:千里之外
    • 原创:25篇
    • 转载:3篇
    • 译文:0篇
    • 评论:0条