Is prototype pattern the right fit here?

101 Views Asked by At

I have an array of type Cell. This is a 2D array. Depending on certain conditions, I might have to resize this array and shift the Cell objects one row or column down/right/left.

I was thinking of using the prototype pattern to copy the original array into another larger array.

Does this offer any more benefits over simply doing an array resize?

Edit: I realized that I have not mentioned my intent. I don't really need another object. I just want a larger array based on certain conditions.

2

There are 2 best solutions below

1
On

The only reason this could be of help is if you are making a shallow copy: copying would save you the costs of creating new objects. The flip side of it is that all Cell objects inside the array would be shared among multiple 2D arrays; if this presents a problem, you should go back to creating arrays from scratch.

2
On

Short answer No.

There is an alternative solution that will solve your problem without needing a prototype.

Don't store the cells in an array. The cells don't know their row and column numbers but instead ask the row/column for it. This allows the columns to be rearranged without having to update every item.

Have a container object that represents the array and can return the cell at a given (x,y) coordinate. If the array is sparce (or if it has a sensible default) then treat a missing cell as the default. This will massively reduce storage costs. The columns and rows belong to the container. Adding an empty row or column now becomes a case of inserting a row or column object.