Book Image

Learning Java by Building Android Games - Second Edition

By : John Horton
Book Image

Learning Java by Building Android Games - Second Edition

By: John Horton

Overview of this book

Android is one of the most popular mobile operating systems presently. It uses the most popular programming language, Java, as the primary language for building apps of all types. However, this book is unlike other Android books in that it doesn’t assume that you already have Java proficiency. This new and expanded second edition of Learning Java by Building Android Games shows you how to start building Android games from scratch. The difficulty level will grow steadily as you explore key Java topics, such as variables, loops, methods, object oriented programming, and design patterns, including code and examples that are written for Java 9 and Android P. At each stage, you will put what you’ve learned into practice by developing a game. You will build games such as Minesweeper, Retro Pong, Bullet Hell, and Classic Snake and Scrolling Shooter games. In the later chapters, you will create a time-trial, open-world platform game. By the end of the book, you will not only have grasped Java and Android but will also have developed six cool games for the Android platform.
Table of Contents (30 chapters)
Learning Java by Building Android Games Second Edition
Contributors
Preface
Index

The Singleton pattern


The Singleton pattern is as the name suggests is a pattern that is used when we want only one of something. And more importantly, that we need to absolutely guarantee we only have one of something. The something I refer to is an instance of a class. Furthermore, the Singleton pattern is also used when we want to allow global access to some of its data or methods. The class can then be used from anywhere within a project and yet is also guaranteeing that all parts/classes of the project that access the class are using the exact same instance.

Part of the Singleton conundrum is simple. To make parts of it available to any other class you simply make the methods public and static.

Note

See Chapter 8: Object-Oriented Programming for a reminder about static variables.

But how do we guarantee that only one instance can ever be created? We will look at the code next but as a look-ahead what we will do is create a class which has a private constructor. Remember that a private method...