One of the cocos2d-x design pattern Excavations: single-case mode

Source: Internet
Author: User
Tags notification center

Author: firedragonpzy original address: http://www.firedragonpzy.com.cn/index.php/archives/1781

In this series, I will work with you to discover the design patterns used in cocos2d-x, and in the same way, these patterns can be found in Cocos2d-iphone.

Disclaimer: The excavation mode here is just my personal hobby, and through this process I hope to deepen my understanding of the use of design patterns. On the mode of learning, there are already many very good books on the market. such as "Head first design mode", Gof design mode, as well as "grinding design mode" and so on. If the reader does not understand the design pattern at all, it is recommended to read at least one of the above books before reading this series of articles before you understand design patterns. In this way, everyone will have a common language to communicate with each other.

Why Explore Design Patterns? Because the design pattern itself is people in some object-oriented software system in the excavation, under a certain scenario can be reused solution. Through the mining of patterns, I can take this opportunity to learn about these excellent design ideas. Because I think a good open source game framework in addition to the development of our developers to bring efficiency, but also should be absorbed by our design ideas, so that its value can be complete.

This series of articles will be based on the following ideas for pattern mining:

1. Find out the application scenario for a design pattern (class, class structure, object structure, combined with UML class diagrams if necessary)

2. Analyze why this pattern is used (i.e. design decisions)

3. What are the pros and cons of using this mode (any transaction has two sides, design mode is no exception)

4. Definition and general implementation of this mode (this is in the classic book of Gof, which is borrowed here)

5. How to use this pattern in game development (your own understanding of pattern usage scenarios)

6. Which patterns are often used in this mode (this is basically borrowed from Gof's books)

The single example in 1.cocos2d-x is as follows:

  • Ccdirector
  • Cctexturecache
  • Ccspriteframecache
  • Ccanimationcache
  • Ccuserdefault
  • Ccnotificationcenter
  • Ccshadercache
  • Ccscriptenginemanager
  • Ccpoolmanager
  • Ccfileutils
  • Ccprofiler
  • Simleaudioengie
  • Ccconfiguration
  • Ccapplication
  • Ccdirectorcaller (iOS platform)
  • Cceglview

Why are there such a few single cases?

The first is the Ccdirector Singleton, which manages the initialization of OpenGL render windows and the process control of the game scene, which is one of the essential classes in COCOS2DX game development. Why should we design this class as a singleton object? Because a game requires only a single game window, it only needs to initialize the OpenGL render window once. and the Process control function of the scene, but also only need to exist one such scene control object. To ensure that only one instance object exists in the Ccdirector class, you must use singleton mode.

Next is the Cctexturecache single case. This class is mainly responsible for loading the game needs of the texture picture resources, these resources are loaded, it can be kept in memory, when the next time you need to use this texture, directly return to the corresponding texture object reference, no need to re-load. Of course, this can be a waste of memory, so COCOS2DX uses a reference count to manage object memory, and when the texture has just been loaded, the reference count is 1. If you use this texture object to create a sprite, this texture object reference will add 1. If the sprite is freed, the corresponding reference count is reduced by 1. When the reference count of the texture becomes 0, the memory used by the texture will naturally be released. This is why the Removeunusedtextures method of Cctexturecache is called when a memory warning is received. This method frees all texture objects that have a reference count of 1. The single literal, the cache, is the meaning of caching. It is at the expense of a certain amount of memory pressure to bring the game performance improvement. This cache technology is ubiquitous in game development. Note: IO operation has a great impact on game performance, so try to avoid it!!!

Similar to Ccspriteframecache, Ccanimationcache, and Ccshadercache, they are also cache classes that are responsible for caching spriteframe, animation, and shader respectively. The reason for this is nothing more than performance, space-changing time.

Next, look at Ccuserdefault. This class is primarily used to save the data in the game, it creates an XML file, and stores the user-defined data in this XML file in key-value form. Why does this class become a singleton class? The reason is also simple, because a class like this operation data file, or a configuration file, usually requires only one instance to exist during the program's run.

Then Ccnotificationcenter, which is a notification center, actually uses an observer pattern, which is not discussed here for the time being. This notification center is also theoretically only needed one is enough. However, cocos2d-x in implementing this singleton, does not have this kind of constructor private, I guess, is not the developer intentionally? or multiple notification hubs also have value for their existence. We can talk about this for a moment.

Ccscriptenginemanager, this class contains an object reference that implements the Ccscriptengineprotocl interface, which helps us to easily locate the Luaengine object. The role of the singleton here is purely a global access point for luaengine. Why not just take luaengine as a singleton object? Is it possible to create multiple Luaengine objects under certain circumstances? If you consider that Cocos2d-x can also support other scripting engines, you can also design additional scripting engines as singleton classes. Of course, this will undoubtedly lead to an excessive number of singleton in the engine. Considering that the singleton model has been criticized by many developers in recent years, it has been listed as "anti-pattern". This is also a way of referencing the Ccscriptenginemanager Singleton class, which provides the only global point of access to other engine objects. I wonder if my speculation is correct?

Ccpoolmanager, this class is used to manage the Autoreleasepool object stack. Because Cocos2d-x uses a reference count-based approach to managing dynamic memory, managed objects with reference counts are placed inside a current autoreleasepool. When the mainloop of Ccdirector is updated every time, the Ccpoolmanager pop method is called, and the managed state of all Autorelease objects inside the current Autoreleasepool is set to false. At the same time, the Autoreleasepool is emptied, and when emptied, the release method of all objects in Autoreleasepool is called to free memory.   Why should this class be designed with a single case? Because this class needs to be referenced in many places, it is designed to be a singleton for easy reference.

Then the Ccfileutils class. This class is a tool class. Tool classes and configuration file classes, most of which are also designed in singleton cases. Because they do not have multiple instances to be necessary. At the same time, they can also be implemented as a set of class methods that can be used without creating objects.

Then there is the Ccprofiler class, which is responsible for the performance of Cocos2d, which is also a tool class. So the reason it is designed as a singleton class is similar to the Ccfileutils class.

The Ccconfiguration class is also designed as a singleton object, which is primarily responsible for managing some of the OpenGL variable information for cocos2d-x. This information can be resolved by defining some macros, or by some global variables. The design of the Singleton class is also a more "object-oriented" embodiment. Because these configuration information does not need to have more than one object at all.

The Ccapplication class was designed to get some information about the platform and, most importantly, to run the main loop of the game (main loop). A game requires only one application instance, so design with Singleton.

Cceglview is cocos2d-x for Eglview abstraction, different platforms will have different implementations, so that they can be applied to different platforms. On the iOS platform it is a simple package for eaglview. This class represents an abstraction of the OpenGL rendering context window, which is a virtual resource and is designed as a singleton class only if there is a possibility of one instance.

The Ccdirectorcaller class is an iOS platform-related class that is an encapsulation of the iOS platform Ccdirector object, using Cadisplaylink to run the game's main loop. This class is similar to the Ccdirector class and can also be designed as a single case. Why the Ccdirectorcaller class is called in the Ccapplication class, is based on the separation of platform-related code considerations. Ccapplication Yes, Ccdirectorcaller is too.

The last one is the Simpleaudioengine class, which is also designed as a singleton class. Because it gives developers the simplest sound operation interface, it's easy to handle the background music and sound effects in the game. This class also applies the appearance mode, the complex function in the cocodenshion subsystem is shielded, simplifying the client programmer's call. Why this class is designed to be a singleton is because it is accessed everywhere. It is convenient to design a single meeting, and it is not related to other objects, and it is not good to use object combination.

2. Advantages and disadvantages of using singleton mode

Pros: Easy to use, limiting a class to only one instance can reduce the risk of memory problems that may arise from creating multiple objects, including memory leaks, memory consumption issues.

Cons: Singleton mode because it provides a global access point, you can easily access it from anywhere in the program, which is a highly coupled design in itself. Once the singleton changes, the other templates need to be modified. In addition, the singleton mode makes the object become global. People who have learned to deal with object programming know that global variables are very evil and try not to use them. And the singleton pattern makes the object's memory persist until the end of the program, in some languages that use GC, which is actually a memory leak because they are never released. Of course, you can also provide some methods to release the memory occupied by the Singleton object, such as the Xxxcache object mentioned earlier, there is a corresponding purge method. Finally, the single example implemented in COCOS2DX, 99% is not thread-safe.
In discussing the pros and cons, the reader must have seen, the shortcomings of more than the advantages. This is to give you a wake up, in the future use of the singleton mode should be cautious, do not misuse. Because this mode is most likely to be abused. Only when you really fit into the scenario of a singleton pattern can you consider it. Do not make a single case of any class for easy access, so that, in the end, you will find that only a bunch of singleton and factory are left in your program.
In addition, the singleton pattern is being reduced, such as Ccactionmanager and Cctouchdispatcher before cocos2d1.0, which is now a property of the Ccdirector class. and Riq (Cocos2d-iphone's author) also mentions in the mail that later Ccdirector objects become non-singleton, and allow a game to create multiple game windows.

3. Definition of a singleton mode: guarantees that a class has only one instance and provides a global access point to access it.

Its general implementation is as follows:

 Public classsingleton{ Public:   //Global access Point   Staticsingleton*Sharedsingleton () {if(NULL = =M_spsingleton) {M_spsingleton=NewSingleton (); }       returnM_spsingleton; }  Private:  Staticsingleton*M_spsingleton;  Singleton (); Singleton (Constsingleton&Other ); Singleton&operator=(Constsingleton&Other );}; Singleton* Singleton::m_spsingleton = NULL;

Note that this is only the most basic implementation, which does not take into account thread safety, nor does it consider memory deallocation. However, this implementation has two most basic elements.
One: Define a static variable and set the constructor to private. Two: Provide a global access point for external access.

4. How to use this mode in game development? As we all know, game development is inseparable from the game data storage and loading. This data includes level data, status data in the game in progress, and so on. Such information is required to be accessed in many game modules, so you can set up a singleton object for it. I arbitrarily think that in client-side game development, at least one singleton object is required. Because a global access point can facilitate the interaction between many objects. Depending on the previous discussion, you can also save some of the class references that you need to use in this singleton, but you only need to save the weak references. Using Singleton, the most serious is afraid of memory leaks, so, we try not to put the Singleton class design too complex, and do not let it contain too much dynamic memory management work.

5. The singleton mode is generally used in conjunction with the factory model, as the factory class is generally designed as a singleton object. such as the various cache classes mentioned earlier, they can also be regarded as a kind of factory object in a sense. Because the factory is responsible for the production of objects, and the cache class can be based on the needs of users to produce the corresponding object.

Finally, look at Cocos2d-x founder Wang Zhe's view of what a singleton is:
"Let's just say that I designed the singleton as an abstract case: an exclusive resource. For example, a hardware IO (such as Cctouchdispatcher, Ccaccelerometer), such as a common buffer (Cctexturecache, Ccuserdefault). Later people complained that the Singleton class too much, want to destroy the whole cocos2d instance reconstruction is very troublesome, so Xiao Ming and Riq put a large number of singleton class into the ccdirector inside management. ”
Excerpt from: http://www.zilongshanren.com/cocos2d-x-design-pattern-singleton1/comment-page-1/#comment-20

  

Welcome to follow Dongsheng Sina Weibo @tony_ Dongsheng.

Learn about the latest technical articles, books, tutorials and information on the public platform of the smart Jie classroom

More Products iOS, Cocos, mobile design courses please pay attention to the official website of Chi Jie Classroom: http://www.zhijieketang.com

Luxgen Classroom Forum Website: http://51work6.com/forum.php

One of the cocos2d-x design pattern Excavations: single-case mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.