The double buffer behavioral pattern allows multiple changes to all appear to occur at the same time.

This is a simple pattern that’s used anytime you need not just synchronization between readers of information and writers of that same information but when you need the readers to have access to the current information while the writers are updating a new version. Once everything is ready, then the next version becomes the current and the old current version is recycled and used for the new next version.

This design pattern also starts a new series of design patterns focused more on game development. This pattern can be found in the book “Game Programming Patterns” by Robert Nystrom. I recommend this book in addition to listening to my audio explanation because the author has an explanation that’s designed for the written page.

The most common application of this pattern in game programming is probably the screen updates. It takes a while to draw each frame as it needs to appear. And this process usually starts with a blank canvas and gets built up bit by bit. Some parts can even get updated multiple times as some image is drawn and then overwritten by some other image. Only once the frame is completely drawn should it be sent to the screen. During the time the new frame is being drawn, it’s possible that the video card will need to be refreshing the screen on its own schedule. By updating a separate buffer, your application can let the video card use the current frame until the new one is ready.

This pattern can help not just with video refreshes. You can also manage class property values in the same way. If you have an object with lots of properties and you want to update some of them but the update really needs to be done all at once in order to make any sense, then this pattern can help. You’ll need to keep two copies of the data in memory with some way to switch between them. The easiest way to switch is to maintain two pointers, a current pointer and a next pointer.

I didn’t mention this in the audio but you can also use this pattern for cancelling updates. Let’s say you have a dialog box where the user can enter different values in data fields. The dialog box will have an Ok and a Cancel button. While changes are being made, put the new values in the next buffer. If the user commits the changes, then swap the buffers. And if the user cancels, then you don’t need to worry about restoring anything because you left all the original data unchanged. The Cancel button just causes the second buffer to be discarded. Or you can just clear it and be ready for another possible update.