| Start |
|---|
| Implementing map in RPG game Flyweight is one of structural design patterns. It is used to decrease the amount of used memory by sharing as much data as possible with similiar objects. This document will teach you how to use Flyweight DP properly. Let me explain the idea of it to you on a simple example. Imagine you're working on a RPG game and you need to load huge file that contains some characters. For example:
Sample of a map:
Since those objects have similiar characteristic, you don't need to create separate object for each map field. I will show you how to use flyweight. Let's define an interface which our fields will implement: Now we can create classes that represent our fields. We also have to identify them somehow (I used an enumeration): Like I said, we don't need to create separate instance for each field. We have to create a repository of fields. The essence of Flyweight DP is that we dynamically create an object only if we need it and it doesn't exist yet in our repo, or return it if it already exists. Let's write simple class that will handle this for us: Great! Now we can test our code: The result in the console should be: Created a new instance of Grass Created a new instance of Rock But why grass appears only one time if we wanted to get it twice? That's because first time we call |
Read Article
https://develop.horje.com/learn/1434/reference