mardi 12 juillet 2016

How to employ the factory pattern where the constructor arguments vary

I'm writing a package where I need to have PHP objects represent MySQL data types.

For example, I have classes for IntType, VarCharType, BlobType, etc.

Each of these have different constructor arguments. I.e. IntType has a signed property, VarChar has collation, etc.

The source for which of these types I need to construct from from the database. So I may have "INT(10) UNSIGNED", "VARCHAR(255)", and "BLOB".

So currently I have a method that examine and pull apart these strings, and it uses a lot of IF and SWITCH statements to determine which class needs to be constructed.

I know this is ugly but I'm not sure on the best way around it. All textbook examples of the Factory pattern are based on producing classes that have identical constructor arguments.

Currently I have two ideas to solve this:

  • Use something like the Chain Of Responsibility pattern, where I have a factory per data type, and each will decide if it can handle the data type string, and if it can't it will be passed onto the next factory.
  • Have a factory per data type, and a super factory that would examine the data type string to determine the correct data type factory to handle the string.

Because I have not see much theory on this, I'm a little unsure of the most ideal direction.

Aucun commentaire:

Enregistrer un commentaire