constructor methods in interfaces

后端 未结 6 2164
闹比i
闹比i 2021-02-18 21:03

Are constructor methods in interfaces bad?

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-18 21:20

    You have to instantiate immutable polymorphic objects sometime via their constructor that requires parameters and you may need that constructor in the interface for the exact same reasons you may need the other public methods in the interface, for example…

    Say you have to instantiate a polymorphic object, its class implementing your interface and being supplied by the client code. As a dumb but simple scenario let's say this object is a value object and as such should be immutable, which mean the object's state should be valid from the moment it's instantiated…

    $immutablePolymorphe = $userConfig['immutable_polymorphe_class'];
    $immutablePolymorphe = new $immutablePolymorphe($state);
    // Then do something with that polymorphe...
    

    So what if you don't define the constructor with its parameter in the interface? Hence the reason why I believe a constructor in an interface can be as much legitimate as any other public method in an interface…

提交回复
热议问题