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

Game Development Patterns and Best Practices: Better games, less hassle

Arrow left icon
Profile Icon Casanova Profile Icon John P. Doran
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (1 Ratings)
Paperback Apr 2017 394 pages 1st Edition
eBook
$27.98 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Casanova Profile Icon John P. Doran
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (1 Ratings)
Paperback Apr 2017 394 pages 1st Edition
eBook
$27.98 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$27.98 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Game Development Patterns and Best Practices

One Instance to Rule Them All - Singletons

Now that we've learned what a design pattern is, as well as why we'd want to use them, let's first talk about a design pattern that most people learn, the Singleton pattern.

The Singleton pattern is probably the most well-known pattern and it is also the one out there that is most often misused. It definitely has the most controversy surrounding it, so when discussing this pattern it is as important (or even more important) to know when not to apply it.

Chapter overview

In this chapter, we will explain about the pattern and many arguments for and against it. We will describe how and why core systems within the Mach5 engine such as the Graphics Engine and Object Manager are utilized as Singletons. Finally, we will explain a number of different ways to implement this in C++, along with the pros and cons of each choice.

Your objective

This chapter will be split into a number of topics. It will contain a simple step-by-step process from beginning to end. Here is the outline of our tasks:

  • An overview of class access specifiers
  • Pros and cons of global access
  • Understanding the static keyword
  • What is a Singleton?
  • Learning about templates
  • Templatizing Singletons
  • The advantages and disadvantages of only one instance
  • The Singleton in action: the Application class
  • Design decisions

An overview on class access specifiers

When using an object-oriented programming language, one of the most important features included is the ability to hide data, preventing classes from accessing properties and functions of another class type by default. By using access specifiers such as public, private, and protected, we can dictate specifically how the data and/or functions can be accessed from other classes:

class ModifierExamples 
{
public int publicInteger;
private void PrivateMethod() {}
protected float protectedNumber;
};

A class can have unlimited variables or functions that are public, private, or protected and can even control access to entire sections of the class:

class MoreModifierExamples 
{
public:
// until we reach another tag, all variables and functions
// will be public
int publicIntegar;
int anotherExample;

private:
// Now, they'll be private
void PrivateFunction...

The static keyword

Another thing that is important to know before diving into the Singleton pattern is what the static keyword means, as it's something that we will be using the functionality of when building this pattern. When we use the static keyword, there are three main contexts that it'll be used in:

  • Inside a function
  • Inside a class definition
  • In front of a global variable in a program with multiple files

Static keyword inside a function

The first one, being used inside of a function, basically means that once the variable has been initialized, it will stay in the computer's memory until the end of the program, keeping the value that it has through multiple runs of the function. A simple example would be something like this:

#include <string...

Chapter overview


In this chapter, we will explain about the pattern and many arguments for and against it. We will describe how and why core systems within the Mach5 engine such as the Graphics Engine and Object Manager are utilized as Singletons. Finally, we will explain a number of different ways to implement this in C++, along with the pros and cons of each choice.

Your objective


This chapter will be split into a number of topics. It will contain a simple step-by-step process from beginning to end. Here is the outline of our tasks:

  • An overview of class access specifiers
  • Pros and cons of global access
  • Understanding the static keyword
  • What is a Singleton?
  • Learning about templates
  • Templatizing Singletons
  • The advantages and disadvantages of only one instance
  • The Singleton in action: the Application class
  • Design decisions

An overview on class access specifiers


When using an object-oriented programming language, one of the most important features included is the ability to hide data, preventing classes from accessing properties and functions of another class type by default. By using access specifiers such as public, private, and protected, we can dictate specifically how the data and/or functions can be accessed from other classes:

class ModifierExamples 
{ 
  public int publicInteger; 
  private void PrivateMethod() {} 
  protected float protectedNumber; 
};

A class can have unlimited variables or functions that are public, private, or protected and can even control access to entire sections of the class:

class MoreModifierExamples 
{ 
  public: 
    // until we reach another tag, all variables and functions  
    // will be public 
    int publicIntegar; 
    int anotherExample; 

  private: 
    // Now, they'll be private 
    void PrivateFunction() {} 
    double safeValue; 

  protected: 
    // And now...

The static keyword


Another thing that is important to know before diving into the Singleton pattern is what the static keyword means, as it's something that we will be using the functionality of when building this pattern. When we use the static keyword, there are three main contexts that it'll be used in:

  • Inside a function
  • Inside a class definition
  • In front of a global variable in a program with multiple files

Static keyword inside a function

The first one, being used inside of a function, basically means that once the variable has been initialized, it will stay in the computer's memory until the end of the program, keeping the value that it has through multiple runs of the function. A simple example would be something like this:

#include <string> 

class StaticExamples 
{ 
public: 
  void InFunction() 
  { 
    static int enemyCount = 0; 

    // Increase the value of enemyCount 
    enemyCount += 10; 

    std::string toDisplay = "\n Value of enemyCount:  " +  
                std::to_string...

Pros and cons of global variables


To reiterate, a global variable is a variable that is declared outside of a function or class. Doing this makes our variable accessible in every function, hence us calling it global. When being taught programming in school, we were often told that global variables are a bad thing or at least, that modifying global variables in a function is considered to be poor programming practice.

There are numerous reasons why using global variables is a bad idea:

  • Source code is the easiest to understand when the scope of the elements used is limited. Adding in global variables that can be read or modified anywhere in the program makes it much harder to keep track of where things are being done, as well as making it harder to comprehend when bringing on new developers.
  • Since a global variable can be modified anywhere, we lose any control over being able to confirm that the data contained in the variable is valid. For instance, you may only want to support up to a certain...

What is a Singleton?


The Singleton pattern in a nutshell is where you have a class that you can access anywhere within your project, due to the fact that only one object (instance) of that class is created (instantiated). The pattern provides a way for programmers to give access to a class's information globally by creating a single instance of an object in your game.

Whereas there are quite a few issues with using global variables, you can think of a Singleton as an improved global variable due to the fact that you cannot create more than one. With this in mind, the Singleton pattern is an attractive choice for classes that only have a unique instance in your game project, such as your graphics pipeline and input libraries, as having more than one of these in your projects doesn't make sense.

This single object uses a static variable and static functions to be able to access the object without having to pass it through all of our code.

In the Mach5 engine, Singletons are used for the application...

Learning about templates


Another technique to add to your toolbox of programming concepts that we will use in the next section is the idea of templates. Templates are a way for you to be able to create generic classes that can be extended to have the same functionality for different datatypes. It's another form of abstraction, letting you define a base set of behavior for a class without knowing what type of data will be used on it. If you've used the STL before, you've already been using templates, perhaps without knowing it. That's why the list class can contain any kind of object.

Here's an example of a simple templated class:

#include <iostream> // std::cout 

template <class T> 
class TemplateExample 
{ 
public: 
  // Constructor 
  TemplateExample(); 
  // Destructor 
  ~TemplateExample(); 
  // Function 
  T TemplatedFunction(T); 
};

In this case, we created our TemplateExample class and it has three functions. The constructor and deconstructor look normal, but then I have...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • • Untangle your game development workflow, make cleaner code, and create structurally solid games
  • • Implement key programming patterns that will enable you to make efficient AI and remove duplication
  • • Optimize your game using memory management techniques

Description

You’ve learned how to program, and you’ve probably created some simple games at some point, but now you want to build larger projects and find out how to resolve your problems. So instead of a coder, you might now want to think like a game developer or software engineer. To organize your code well, you need certain tools to do so, and that’s what this book is all about. You will learn techniques to code quickly and correctly, while ensuring your code is modular and easily understandable. To begin, we will start with the core game programming patterns, but not the usual way. We will take the use case strategy with this book. We will take an AAA standard game and show you the hurdles at multiple stages of development. Similarly, various use cases are used to showcase other patterns such as the adapter pattern, prototype pattern, flyweight pattern, and observer pattern. Lastly, we’ll go over some tips and tricks on how to refactor your code to remove common code smells and make it easier for others to work with you. By the end of the book you will be proficient in using the most popular and frequently used patterns with the best practices.

Who is this book for?

If you are a game developer who wants to solve commonly-encountered issues or have some way to communicate to other developers in a standardized format, then this book is for you. Knowledge of basic game programming principles and C++ programming is assumed.

What you will learn

  • • Learn what design patterns are and why you would want to use them
  • • Reduce the maintenance burden with well-tested, cleaner code
  • • Employ the singleton pattern effectively to reduce your compiler workload
  • • Use the factory pattern to help you create different objects with the same creation logic and reduce coding time
  • • Improve game performance with Object Pools
  • • Allow game play to interact with physics or graphics in an abstract way
  • • Refractor your code to remove common code smells

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 27, 2017
Length: 394 pages
Edition : 1st
Language : English
ISBN-13 : 9781787127838
Languages :
Concepts :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Apr 27, 2017
Length: 394 pages
Edition : 1st
Language : English
ISBN-13 : 9781787127838
Languages :
Concepts :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 147.97
Practical Game AI Programming
$54.99
Game Development Patterns and Best Practices
$48.99
Game Physics Cookbook
$43.99
Total $ 147.97 Stars icon

Table of Contents

12 Chapters
Introduction to Design Patterns Chevron down icon Chevron up icon
One Instance to Rule Them All - Singletons Chevron down icon Chevron up icon
Creating Flexibility with the Component Object Model Chevron down icon Chevron up icon
Artificial Intelligence Using the State Pattern Chevron down icon Chevron up icon
Decoupling Code via the Factory Method Pattern Chevron down icon Chevron up icon
Creating Objects with the Prototype Pattern Chevron down icon Chevron up icon
Improving Performance with Object Pools Chevron down icon Chevron up icon
Controlling the UI via the Command Pattern Chevron down icon Chevron up icon
Decoupling Gameplay via the Observer Pattern Chevron down icon Chevron up icon
Sharing Objects with the Flyweight Pattern Chevron down icon Chevron up icon
Understanding Graphics and Animation Chevron down icon Chevron up icon
Best Practices Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(1 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Brenda Reid Oct 01, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Thanks
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.