design patterns - Using a class to store constant values -
is there better approach storing values required per following example. im trying avoid possible errors when passing string factory method.
but, there issues this? testable, there better way achieve same thing etc.
abstract class types { const car = 'car'; const boat = 'boat'; const bike = 'bike'; } class vehiclefactory { public function make($type) { if ($type === types::car) { // create new car } if ($type === types::boat) { // create new boat } if ($type === types::bike) { // create new bike } } } class client { public function createacar() { $vehiclefactory = new vehiclefactory(); $car = $vehiclefactory->create(types::car) } }
this looks language agnostic question going assume advice use enum
instead of abstract
class won't work.
your approach of using constants represent type of object gets created correct. if had change anything, way client
class uses vehiclefactory
provide test doubles while unit testing code :
class client { private $factory; public function __construct($factory){ $this->factory = $factory; } public function createacar() { $car = $factory->create(types::car) } }
now can pass in subclass of vehiclefactory
(say vehiclemockfactory
) can create test doubles instead of creating actual objects :
class vehiclemockfactory extends vehiclefactory { public function make($type) { if ($type === types::car) { // create new testcar } if ($type === types::boat) { // create new testboat } if ($type === types::bike) { // create new testbike } } }
while unit testing, can pass vehiclemockfactory
client
rather actual vehiclefactory
.
Comments
Post a Comment