Reader small image

You're reading from  Game Development Patterns with Unity 2021 - Second Edition

Product typeBook
Published inJul 2021
Reading LevelBeginner
PublisherPackt
ISBN-139781800200814
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
David Baron
David Baron
author image
David Baron

David Baron is a game developer with over 15 years of experience in the industry. He has worked for some well-known AAA, mobile, and indie game studios in Montreal, Canada. His skill set includes programming, design, and 3D art. As a programmer, he has worked on various games for various platforms, including virtual reality, mobile, and consoles.
Read more about David Baron

Right arrow
Adapting Systems with an Adapter

In a world full of different types of cables and plugs, we have all become accustomed to the concept of adapters. The Adapter pattern will be one of those patterns that will be easy for you to grasp because it correlates so perfectly with our real-world experiences with technology. The Adapter pattern's name perfectly reveals its core purpose; it offers us a way to seamlessly use old code with new code by adding an interface between the code that will act as an adapter.

The following topics will be covered in this chapter:

  • Understanding the Adapter pattern
  • Implementing the Adapter pattern
The examples presented in this chapter are skeleton code. It's simplified for learning purposes so we can focus on the structure of the pattern. It might not be optimized or contextualized enough to be used as is in your project.

Technical requirements

Understanding the Adapter pattern

As its name implies, the Adapter pattern adapts two incompatible interfaces; like a plug adapter, it doesn't modify what it adjusts but bridges one interface with another. This approach can be beneficial when dealing with legacy code that you cannot refactor due to its fragility, or when you need to add features to a third-party library but don't want to modify it to avoid issues when upgrading it.

Here's a quick breakdown of the two main approaches to implementing the Adapter pattern:

  • Object Adapter: In this version, the pattern uses object composition, and the adapter acts as a wrapper around the adapted object. It's helpful if we have a class that doesn't have the methods we require, but we can't modify it directly. The Object Adapter adopts the methods of the original class and adapts them to what we need.
  • Class Adapter: In this version of the pattern, the adapter uses inheritance to adapt the interface of an existing...

Benefits and drawbacks of the Adapter pattern

The following are some of the benefits of the Adapter pattern:

  • Adapting without modifying: The main benefit of the Adapter pattern is that it offers a standard approach to adapting old or third-party code without modifying it.
  • Reusability and flexibility: This pattern permits the continued use of legacy code on new systems with minimal changes; this has an immediate return on investment.

The following are some potential drawbacks of the Adapter pattern:

  • Persisting legacy: The ability to use legacy code with new systems is cost-effective, but in the long term, it can become an issue, because the old code might limit your upgrade options as it becomes deprecated and incompatible with new versions of Unity or third-party libraries.
  • Slight overhead: Because, in some instances, you are redirecting calls between objects, there might be a slight performance hit, usually too small to become an issue.
The Adapter is part of the structural...

When to use the Adapter pattern

A potential use case for the Adapter in Unity is when you have a third-party library that you downloaded from the Unity Asset Store, and you need to modify some of its core classes and interfaces to add new features. But when changing third-party code, you risk having merge issues every time you pull an update from the library owners.

Hence, you find yourself in a situation where you choose to wait for the third-party library owners to integrate the changes you need or modify their code and add the missing features. Both choices have their risks versus rewards. But the Adapter pattern gives us a solution to this dilemma by letting us place an adapter between existing classes so they can work together without modifying them directly.

Let's imagine we are working on the code base of a project that uses an inventory system package downloaded from the Unity Asset Store. The system is excellent; it saves the player's purchased or gifted inventory items...

Implementing the Adapter pattern

The code example will be simple; we will not attempt to write an entire local disk save system because that's not the focus of this chapter. Instead, we will write the skeleton of the system to concentrate on the use of the Adapter pattern and not be impeded by unrelated implementation details.

Implementing the Adapter pattern

To start off, we will implement a placeholder class that will mock the third-party inventory system as presented in the scenario of the previous section:

  1. The InventorySystem class provided by our fictional provider has three methods, AddItem(), RemoveItem(), and GetInventory(). All of these methods are hardcoded to use cloud storage and we can't modify them:
using UnityEngine;
using System.Collections.Generic;

namespace Chapter.Adapter
{
public class InventorySystem
{
public void AddItem(InventoryItem item)
{
Debug.Log(
"Adding item to the cloud");
}

public void RemoveItem(InventoryItem item)
{
Debug.Log(
"Removing item from the cloud");
}

public List<InventoryItem> GetInventory()
{
Debug.Log(
"Returning an inventory list stored in the cloud");

return new List<InventoryItem...

Testing the Adapter pattern implementation

To test our implementation in your instance of Unity, copy all the classes we just reviewed into your project and attach the following client class to an empty GameObject in a new Unity scene:

using UnityEngine;

namespace Chapter.Adapter
{
public class ClientAdapter : MonoBehaviour
{
public InventoryItem item;

private InventorySystem _inventorySystem;
private IInventorySystem _inventorySystemAdapter;


void Start()
{
_inventorySystem = new InventorySystem();
_inventorySystemAdapter = new InventorySystemAdapter();
}

void OnGUI()
{
if (GUILayout.Button("Add item (no adapter)"))
_inventorySystem.AddItem(item);

if (GUILayout.Button("Add item (with adapter)"))
_inventorySystemAdapter.
AddItem(item, SaveLocation.Both);
}
}
}

We now can build a new inventory...

Summary

In this chapter, we added the Adapter pattern to our toolbox. It's a type of pattern that's very beneficial to have in our back pocket. One of the biggest challenges for a professional programmer is dealing with incompatible systems that are often developed by external vendors or other teams inside an organization. A consistent approach to adapting existing classes can only be helpful, especially when time becomes an issue and it's just faster to reuse old code for new purposes.

In the next chapter, we will review a close cousin of the Adapter, the Facade pattern, which we will use to manage the growing complexity in our code.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Game Development Patterns with Unity 2021 - Second Edition
Published in: Jul 2021Publisher: PacktISBN-13: 9781800200814
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.
undefined
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 €14.99/month. Cancel anytime

Author (1)

author image
David Baron

David Baron is a game developer with over 15 years of experience in the industry. He has worked for some well-known AAA, mobile, and indie game studios in Montreal, Canada. His skill set includes programming, design, and 3D art. As a programmer, he has worked on various games for various platforms, including virtual reality, mobile, and consoles.
Read more about David Baron