Prototype vs Flyweight
Asked Answered
B

2

6

I start to learn design-patterns. I understand that prototype is for making an exact copy of an object I already have and Flyweight is for making similar objects.

I've programmed 2D platformer game like Mario (in Java). There are a lot of enemies which are the same the only difference is their position [x,y]. There are also walls which are built from a huge number of rectangles and again the only difference is their position [x,y].

Is it wise to use some of these design patterns in this particular situation? Should I use prototype to clone objects via cloneable and then set [x,y]?

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

In both scenarios I avoid using new operator but I am not sure which one to use.

Baste answered 22/8, 2015 at 7:21 Comment(0)
F
8

You've got it a bit wrong. Prototype is used to create new instances, Flyweight is used to allow sharing of instances.

Not the best example, but game-wise Prototype would mean that you have an EnemyPrototype (or several) and you create a new enemy from that. In a naive implementation this would duplicate all the data, including the graphics. So for 100 enemies you would have the same image 100 times in memory (not a good thing).

As for Flyweight, you would share the graphics. Not really a very good example for Flyweight pattern, since it can be solved easier without any need for such a pattern (just get the reference to the image from a map or factory or whatever).

As for avoiding the new operator, there's no need. There's no advantage in using clone() over new, rather there are some disadvantages.

Famous answered 22/8, 2015 at 7:39 Comment(0)
B
0

Prototype emerged to reduce creational costs. Since, 'cloning' is not much of a performance gain over using 'new' operator (might be even worse due to copying, casting etc. costs), the real gain is probably in getting rid of heavy operations (like db access) during creation.

Prototype also brings (at least to me) the confusion of being 'shallow' or 'deep' for cloned objects.

In your case, I think sharing the image graphics through Flyweight is wise and I would go for another Flyweight or Object Pool for the master object.

Bentinck answered 27/3, 2017 at 21:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.