douxingmou4533 2013-05-28 18:12
浏览 36
已采纳

如何创建允许加载对象的界面?

I have created an interface meant to be implemented by users. The only real requirements I have is that the user's implement a Save() and a Load() method. Now save is simple, but the problem I'm having is with Load().

In order for Load() to be part of the interface it would need to be an instance method. But the nature of it is to return a new object that has been loaded from a database. This would imply that Load() needs to be defined as static. Static methods aren't enforced by the interface.

How can I require users who implement the interface to write their own code for Load()?

I'm using PHP5.4 which does require that constructor definitions are followed in subclasses, so one thought was to change this into an Abstract Class and define a constructor that takes an $id variable. If it's null we create a new object, if it's set then load the object. I'd much prefer to keep this setup as an interface. There also is some concern of ambiguity and some user implementing their constructor incorrectly. It's easier to document and describe what load() should do.

  • 写回答

1条回答 默认 最新

  • douzhang3898 2013-05-28 18:17
    关注

    Why does "a method that returns an object" immediately mean that it has to be static? Static isn't a blanket "go-to" on object creation - it actually serves a specific purpose.

    Anyway. There is nothing stopping you from defining an interface that requires the implementation of a static method, as follows, if your heart so desires :

    interface MyTestInterface {
       public static function Load();
    }
    class MyTest implements MyTestInterface {
       public static function Load() { 
           echo "Test";
       }
    }
    

    Fiddle: http://codepad.viper-7.com/xcoQZh

    There is nothing stopping you from defining a method requiring implementation, either through an interface or an abstract class, when the method is static. However, consider the actual static use in this case....

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line