Singleton: That is, there is only one class object, and provides global access rights
Characteristics:
1. Constructor private
2. Private static member pointer that identifies whether a singleton instance has been created
3. Provide a getinstance () method to obtain a singleton object
The following are the bullets in the aircraft management class to illustrate, the use and implementation of a single case:
#ifndef _manager_h_#define_manager_h_#include"cocos2d.h";//header file containing enemy aircraft and bullets#include"bullet\bullet.h"; #include"enemy\enemybase.h"; USING_NS_CC;//Bullets and enemy aircraft manager, made a single caseclassmanager{ Public: StaticManager *getinstance (); Static voidManager::freeinstance (void);Private: StaticManager *M_manager; Manager (); BOOLinit (); Public: //Two containers are defined using the following method, and the Get method is implemented, so be sure to note the return value of the GET, which returns a reference//It is recommended that containers do not allocate memory space on the heap, and when we allocate memory space on the stack, we must pass the reference, or we will make a mistake.Vector<enemybase *> & Getenemyvector () {returnM_enemyvector;}; Vector<bullet *> & Getbulletvector () {returnm_bulletvector;};Private: Vector<enemybase *>M_enemyvector; Vector<bullet *>m_bulletvector;};#endif
. cpp files for bullet management classes
#include"Manager.h"Manager* Manager::m_manager =NULL;//initializing an array in the initialization list of the constructorManager::manager (): M_enemyvector (), M_bulletvector () {}manager*manager::getinstance () {if(M_manager = =NULL) {M_manager=NewManager (); } returnM_manager;}voidManager::freeinstance (void){ if(M_manager! =NULL) {Delete M_manager; M_manager=NULL; }}
3. How to use a single case to manage bullets in the home view:
//scene switch Complete callvoidMaingame::onentertransitiondidfinish () {//the function of the parent class must be called FirstLayer::onentertransitiondidfinish (); //add enemy aircraft, add one per second This->schedule (Sel_schedule (Maingame::addenemy),1.0f); //add bullets, generate one bullet every 0.08 seconds This->schedule (Sel_schedule (Maingame::addbullet),0.08f); //Collision DetectionThis->schedule (Sel_schedule (Maingame::ishitenemy), 0.016f);}//Collision DetectionvoidMaingame::ishitenemy (floatTM) {}//Add BulletsvoidMaingame::addbullet (floatTM) {Auto Bullet=bullet::create (); Bullet->initbullet ("Bullet1.png"); Auto Point= Point (m_player->Getpositionx (), M_player->getpositiony () +m_player->getcontentsize (). height/2+Ten); Bullet-SetPosition (point); This-addChild (bullet); //adding bullets to the managerAuto & vector = Manager::getinstance ()Getbulletvector (); Vector.pushback (bullet); Log ("%d", Vector.size ());}
A singleton pattern commonly used in cocos