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.
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.