search
HomeDatabaseMysql Tutorial浅谈cocos2dx(19) 二段构建模式

~~~~我的生活,我的点点滴滴!! 这篇文章将围绕两个疑问点展开 一、什么是二段构建模式? 大家都知道在C中我们一般在构造函数中为对象分配内存空间然后初始化成员变量,比如我们调用了new某个东西,那么在堆上会先为对象分配内存空间,然后调用构造函数

~~~~我的生活,我的点点滴滴!!       


这篇文章将围绕两个疑问点展开


一、什么是二段构建模式?

        大家都知道在C++中我们一般在构造函数中为对象分配内存空间然后初始化成员变量,比如我们调用了new某个东西,那么在堆上会先为对象分配内存空间,然后调用构造函数,在构造函数中完成一些初始化的工作。而二段构建模式就是将内存空间的分配和初始化分开来完成,然后调用一个静态方法来返回这个对象。

        就拿cocos2dx中的Sprite类来说吧,当我们调用Sprite::create()的时候内部先使用new来分配内存空间,然后调用init方法来初始化一些变量的设置。所以cocos2dx中的二段构建模式就是将new分配内存空间和init初始化内容分开来处理,而不是c++传统的做法在构造函数中初始化变量。

Sprite* Sprite::create()
{
	//分配内存
	Sprite *sprite = new Sprite();
	//init初始化
	if (sprite && sprite->init())
	{
		//内存管理的工作
		sprite->autorelease();
		return sprite;
	}
	CC_SAFE_DELETE(sprite);
	return nullptr;
}

上边就是使用二段构建模式的过程,Sprite首先调用new来分配内存空间,然后调用init函数来完成初始化的工作,顺带还做了内存管理的工作,最后返回初始化好的对象。所以看了Sprite的create方法的实现,我们也知道了应该怎么使用这个二段构建模式了吧。

二、为什么要这么用?

       c++程序员来说初始化工作不都是在构造函数中完成的吗,cocos中为何要这么做呢?

     这里引述一下王哲的话:“其实我们设计二段构造时首先考虑其优势而非兼容cocos2d-iphone. 初始化时会遇到图片资源不存在等异常,而C++构造函数无返回值,只能用try-catch来处理异常,启用try-catch会使编译后二进制文件大不少,故需要init返回bool值。Symbian(qt), Bada SDK,objc的alloc + init也都是二阶段构造”。现在大家明白了吧,兼容Cocos2d-iPhone是一个原因,另一个重要的原因是构造函数没有返回值啊,如果加载资源图片的时候不存在怎么办,所以初始化的工作写在init函数中,这个函数返回的bool值用来判断是否初始化成功。使用这种方法还可以强化设计,想想自己写代码的时候是不是因为没有初始化某个成员变量导致了bug,这样做就是提醒你记得要在init中初始化成员变量。通过create静态函数返回的这个对象也实现了Cocos2dx中的内存管理,就不用我们自己麻烦了。还有一个原因是在C++的构造函数中是不能调用虚函数的,为了调用虚函数来完成一些功能就要写在init函数中。



        以上就是二段构建模式的说明了,在我们写cocos程序的时候其实不知不觉就已经在使用这个构建模式了,想一下我们一个类继承了Layer,然后使用了宏CREATE_FUNC(),这不就是create静态方法吗,在init函数中完成了初始化,整个过程就是在用这种设计模式!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools