开发者

Recurring configurations of a certain class: better to create subclasses or a factory?

开发者 https://www.devze.com 2022-12-12 07:19 出处:网络
Short summary: When you want to predefine certain instantiations of a class, is it better to create subclasses or a factory?

Short summary: When you want to predefine certain instantiations of a class, is it better to create subclasses or a factory?

Problem Context

I have a view helper class MyWebserviceUrl that has a bunch of properties. It's purpose is to generate an url.

I would like to be able to have preconfigured instances of this class, so that I don't have to do so many setThis(), setThat() for the same family of MyWebserviceUrl's If I have an url of type a, I would like to get an instance with some defaults that pertains to this type a.开发者_StackOverflow社区

I can solve this by subclass MyWebserviceUrl like so

UrlFamFoo extends MyWebserviceUrl  {…}
UrlFamBar extends MyWebserviceUrl  {…}

I could also create a factory, that given a parameter like 'Foo' can configure a MyWebserviceUrl object for me.

My questions:

  1. Should I go the subclass route, or the factory one?
  2. If you advice a factory, should this be a
    • separate view helper,
    • normal factory class, or
    • method factory($name) in MyWebserviceUrl?

Sidenote: I am currently developing in Zend Framework, but this question is more general I think.


edit1 →To be more specific: I just need some of the properties set to defaults and the rest set on the fly.


Use the Prototype Pattern? Once you've created it the way you want it, create a duplicate the next time you need the same thing. This is useful if you want every property to remain the same.

If you just need some of the properties set to defaults and the rest set on the fly, I'd go with a factory method rather than subclassing. If you really need subclasses, a factory class may be in order.


Subclassing doesn't look like the right solution to me. Think about it: in your example, a UrlFamFoo is just a MyWebserviceUrl with the properties set to certain values. You can take a MyWebserviceUrl object and set its properties so it will behave just like a UrlFamFoo object. Clearly this subclass is unnecessary.

I would use use a factory method, or simply a constructor.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号