What is the proper way to use inheritance when combined with factory method?

67 Views Asked by At

Given that I have 3 classes Asset, AssetA, AssetB what is the proper way to structure inheritance when using the factory method?

Here is how I would like to use these classes:

  • Asset.new(data) should deterministically create either AssetA or AssetB depending on some flag present in data
  • Asset should also act as a super class in a sense that it's methods should also be present in AssetA and AssetB
2

There are 2 best solutions below

0
On BEST ANSWER

I would create a base Asset class and have AssetA and AssetB inherit from it. The factory class should be a separate class - AssetFactory - with just one single responsibility - it should create new Asset object based on some conditions.

0
On

Are you confusing simple factory with Factory Method?

A simple factory is a class (e.g., AssetFactory) that creates instances of the Asset hierarchy (e.g., AssetA or AssetB).

Simple Factory

Factory Method (Gang of Four) has two hierarchies, one of factories and products. I'm not sure how your problem relates to this.

Factory method