lundi 1 août 2022

Swift Design Choice - Protocol or Class? (mimicking Java's Abstract Class)

I'm making Tetris. What is the best solution for shared code amongst the pieces? A class, protocol, or something else?

Tetrimino template capabilities:

func moveDown()
func rotateRight() // based on data table
func rotateLeft()  // based on data table

Each type of piece can rotate and move, but the way it rotates is determined by unique data tables. The data tables are the same between all instances of that piece (e.g. all long pieces rotate in the same way), and there is mainly shared functionality upon initialization.

It would make sense to use a protocol with a static variable for the data tables, and a default constructor that is run by conforming classes before running their unique code.

However, with a protocol, the static variables cannot be overridden, nor can a base initializer be provided that conforming classes can add onto. But if I use a class to get around these problems, then Tetrimino instances can be made, when it should just be a template.

What's the best design pattern for this?

Aucun commentaire:

Enregistrer un commentaire