Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Game Development Patterns and Best Practices

You're reading from   Game Development Patterns and Best Practices Better games, less hassle

Arrow left icon
Product type Paperback
Published in Apr 2017
Publisher Packt
ISBN-13 9781787127838
Length 394 pages
Edition 1st Edition
Languages
Arrow right icon
Authors (2):
Arrow left icon
John P. Doran John P. Doran
Author Profile Icon John P. Doran
John P. Doran
Matt Casanova Matt Casanova
Author Profile Icon Matt Casanova
Matt Casanova
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Introduction to Design Patterns 2. One Instance to Rule Them All - Singletons FREE CHAPTER 3. Creating Flexibility with the Component Object Model 4. Artificial Intelligence Using the State Pattern 5. Decoupling Code via the Factory Method Pattern 6. Creating Objects with the Prototype Pattern 7. Improving Performance with Object Pools 8. Controlling the UI via the Command Pattern 9. Decoupling Gameplay via the Observer Pattern 10. Sharing Objects with the Flyweight Pattern 11. Understanding Graphics and Animation 12. Best Practices

The Factory method pattern


The Factory method pattern is exactly the design pattern we need to solve our problem. The purpose of this pattern is to have a way of creating the derived class that we want without needed to specify the concreate class in our high-level module. This is done by defining an interface for creating objects, but letting subclasses decide which class to instantiate.

In our case, we will create a StageFactory interface with a method called Build that will return a Stage*. We can then create subclasses such as Level2Factory to instantiate our derived classes. Our StageManager class now only needs to know about the Stage and StageFactory abstractions:

Creating a Stage Factory

//StageManager.cpp 
void StageManager::Update() 
{ 
Stage* pStage = m_stageFactory->Build();

pStage->Init(); 

  while(currentStage == nextStage) 
    pStage->Update(); 

pStage->Shutdown(); 
m_StageFactory->Destroy(pStage);//stage must be destroyed
} 

Notice that we have moved the call...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime