Cocos2d-x运行机制-代理模式

前端之家收集整理的这篇文章主要介绍了Cocos2d-x运行机制-代理模式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Cocos2d-x的入口:

CCApplicationProtocol接口:定义通用接口

// CCApplicationProtocol.h
#pragma once

class CCApplicationProtocol
{
public:
    CCApplicationProtocol();
    virtual ~CCApplicationProtocol();

    virtual bool applicationDidfinishLauching() = 0;
};

CCApplication处理跨平台特性:

//CCApplication.h
#pragma once
#include "CCApplicationProtocol.h"

class CCApplication : public CCApplicationProtocol
{
public:
    CCApplication();
    virtual ~CCApplication();

    int run();

    static CCApplication* sharedApplication();

    static CCApplication* sm_pSharedApplication;

};
//CCApplication.cpp

#include "CCApplication.h"
#include "stddef.h"

CCApplication* CCApplication::sm_pSharedApplication = NULL;

CCApplication::CCApplication()
{
    sm_pSharedApplication = this;//子类对象,其实就是APPDelegate对象
}


CCApplication::~CCApplication()
{
}

int CCApplication::run()
{
    applicationDidfinishLauching();

    return 0; 
}

CCApplication* CCApplication::sharedApplication()
{
    if (sm_pSharedApplication != NULL)
        return sm_pSharedApplication;
    else
        return NULL;
}

APPDelegate实现CCApplication

//AppDelegate.h

#pragma once
#include "CCApplication.h"

class AppDelegate : private CCApplication
{
public:
    AppDelegate();
    virtual ~AppDelegate();

    //主要实现CCApplicationProtocol中的接口
    virtual bool applicationDidfinishLauching();
};
//AppDelegate.cpp

#include "AppDelegate.h"
#include <iostream>


AppDelegate::AppDelegate()
{
}


AppDelegate::~AppDelegate()
{
}

//此方法才是程序的真正入口
bool AppDelegate::applicationDidfinishLauching()
{
    std::cout << "Game Start..." << std::endl;

    return true;
}

测试程序:

//main.cpp

#include <iostream>
#include "CCApplication.h"
#include "AppDelegate.h"

void main()
{

    AppDelegate app;//完成CCApplication的初始化

    //app初始化了CCApplication的静态成员sm_pSharedApplication
    //CCApplication::sharedApplication()得到的就是sm_pSharedApplication
    //然后CCApplication调用自身的run方法,run()中调用CCApplicationProtocol接口中的虚方法,而这些虚方法最终是在APPDelegate中的实现的。
    CCApplication::sharedApplication()->run();

    system("pause");
}
原文链接:/cocos2dx/339041.html

猜你在找的Cocos2d-x相关文章