Prototype against flies

I'm starting to learn design patterns. I understand that the prototype is designed to make an exact copy of the object that I already have, and Flyweight is designed to create similar objects.

I programmed a 2D platform game such as Mario (in Java). There are many enemies that are the same with the only difference in their position [x,y] . There are also walls that are built from a huge number of rectangles, and again the only difference is their position [x,y] .

Can some of these design patterns be used in this particular situation? Should I use a prototype to clone objects by cloning and then set [x,y] ?

Is it better to use flyweight - when I need a new object, I just return them from my hashmap and then set [x, y]?

In both scenarios, I avoid using the new operator, but I'm not sure which one to use.

+5
source share
2 answers

This is a little wrong with you. Prototype used to create new instances, Flyweight used to share instances.

Not a good example, but the game-wise Prototype means that you have EnemyPrototype (or several), and you create a new enemy from it. In a naive implementation, this duplicates all the data, including the graphics. Thus, for 100 enemies you will have the same image 100 times in memory (not very good).

As for Flyweight , you can share the graphics. Not a very good example for a Flyweight template, as it can be easily solved without any need for such a template (just get a link to the image from a card or factory or something else).

As for excluding the new operator, there is no need. There is no advantage to using clone() over new , but there are some disadvantages.

+6
source

A prototype has appeared to reduce the cost of creation. Since “cloning” is not a big advantage when using the “new” operator (maybe even worse due to copying, casting, etc.), the real gain is probably to get rid of heavy operations (for example, access to db) during creation.

The prototype also brings (at least to me) the confusion of being “shallow” or “deep” for cloned objects.

In your case, I think that sharing images with Flyweight is wise, and I would go to another Flyweight or Object Pool for the main object.

0
source

All Articles