dpq39825 2011-04-29 20:11
浏览 38
已采纳

构建一个单身人士班

An ethical question here.

I'm planning on using several manager classes in my new project that will be performing various tasks across the whole project. These classes are singletons, but require construction based on parameters.

As to when/where this construction has to happen, I have mixed feelings. I have these options so far:

Option A

It's easy to just pass these parameters to the getInstance method while having a default null value. On the very first call the parameters will be used, and any additional calls completely ignore them.

While this works, doing so feels rather unlogical, for the following reasons:

  • It makes documentation unclear. getInstance' first parameter must be of type Collection, but can be null... what's going on here? You can argue that writing a line about this in the description will clear it up, but I'd prefer clarification to be unneccesary.

  • It feels faulty to pass getInstance any construction parameters. This is due to the fact that the method name does not explicity hint towards construction, making it unclear it will happen.

Option B

I'm thinking about a setup method. This method takes all parameters, calls the class constructor, and changes the internal class state to initialized.

When calling the getInstance method prior to setup, it will throw a NotInitializedException. After setup has been called, any additional calls to setup will result in a PreviouslyInitializedException.

After setup has been called, getInstance becomes available.

Personally, this option appeals more to me. But it feels excessive.

What option do you prefer? And why?

  • 写回答

5条回答 默认 最新

  • doupo2633 2011-04-29 20:20
    关注

    I would probably try and ditch the singleton approach and pass manager classes around to whatever needs them.

    $manager = new Manager( $collection, $var, $var2 );
    
    $other_class = New OtherClass( $manager );
    //or
    $other_class = New OtherClass;
    $other_class->manager = $manager;
    //or
    $other_class = New OtherClass;
    $other_class->setManager( $manager );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?