Factory in Java when concrete objects take different constructor parameters

后端 未结 4 620
没有蜡笔的小新
没有蜡笔的小新 2021-01-30 20:12

I\'m trying to implement a Factory pattern in Java. I have a class called Shape which Circle and Triangle extends. The problem is that Shape constructor gets only 2 parameters w

4条回答
  •  清歌不尽
    2021-01-30 21:03

    All of your implementations must take the same number of arguments, you have three options:

    • have the factory store the addition arguments so you only need to provide the centre for example.
    • have the factory take all arguments even though some factories might ignore some of them.
    • have an argument be variable length. e.g. 'double...' the problem with this is the caller needs to know what the factory needs which defeats the purpose of a factory. IMHO.

提交回复
热议问题