//ButtonDelegate.h
#pragma once
class ButtonDelegate
{
public:
virtual void onClick(int tag) = 0;
};
//Button.h
#pragma once
#include "ButtonDelegate.h"
class Button
{
public:
Button();
void setTag(int tag);
void setDelegate(ButtonDelegate* delegate);
void click();
private:
ButtonDelegate* m_delegate;
int m_tag;
};
//Button.cpp
#include "Button.h"
Button::Button()
{
m_delegate = nullptr;
}
void Button::setTag(int tag)
{
m_tag = tag;
}
void Button::setDelegate(ButtonDelegate* delegate)
{
m_delegate = delegate;
}
void Button::click()
{
if (m_delegate != nullptr)
{
m_delegate->onClick(m_tag);
}
}
//GameLayer.h
#pragma once
#include "ButtonDelegate.h"
class GameLayer : public ButtonDelegate
{
public:
void onClick(int tag);
void init();
};
//GameLayer.cpp
#include "GameLayer.h"
#include <stdio.h>
#include "Button.h"
void GameLayer::onClick(int tag)
{
printf("--- you click button %d ---\n", tag);
}
void GameLayer::init()
{
Button* btn = new Button();
btn->setTag(1);
btn->setDelegate(this);
btn->click();
}
//main.cpp
#include <stdio.h>
#include "GameLayer.h"
int main(void)
{
GameLayer* layer = new GameLayer();
layer->init();
getchar();
return 0;
}