【问题标题】:How to decorate getter function that implements read-only property?如何装饰实现只读属性的getter函数?
【发布时间】:2015-11-19 17:23:02
【问题描述】:

我想创建灵活的逻辑,允许通过接口操作复杂的包装对象。但有时这些对象可能只是它们“包装”的简单对象的一个​​实例。像这样的:

interface ICoords {
    var x:Float;
    var y:Float;
}

interface ICoordsAccess {
    var coords(default, null):ICoords;
}

class DumbAccess implements ICoordsAccess implements ICoords {
    // ICoordsAccess interface
    public var coords(default, null):ICoords;

    // ICoords interface
    public var x:Float;
    public var y:Float;

    public function new() {
        coords = this; // ...dumb...
    }
}

class SmartAccess implements ICoordsAccess implements ICoords {
    // ICoordsAccess interface
    public var coords(get, null):ICoords; // doesn't comply with interface signature

    function get_coords() return this; // CUTE!

    // ICoords interface
    public var x:Float;
    public var y:Float;

    public function new() {
        // empty constructor
    }
}

class WrapperAccess implements ICoordsAccess {  
    // ICoordsAccess interface
    public var coords(default, null):ICoords;

    public function new() {
        coords = new DumbAccess(); // or SmartAccess doesn't matter
    }
}

使用IObjectAccess 实例运行的代码并不关心它是什么。我可以使用具有常量值的具体实例或根据自己的逻辑更改它们的包装器。

但我想通过替换 getter 函数(可能是内联?)来巧妙地遵守 haxe 只读访问签名 (default, null),该函数排除了在真实类变量中存储 this 引用。签名(get, null)不符合接口的要求,但保证变量是真实的,而不只是替代getter/setter函数。

我的计划可以实现吗?或者我应该改变我的任务方法?

【问题讨论】:

    标签: wrapper getter haxe


    【解决方案1】:

    我决定在核心ICoordsAccess 接口中使用coords(get, null) 访问。然后我以“SmartAccess”风格实现这个签名:

    inline function get_coords() return this;
    

    我不确定这个函数是否已经内联了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-04
      • 2011-04-24
      • 2017-11-28
      • 2014-06-21
      • 2019-12-26
      • 1970-01-01
      • 2021-12-09
      • 2023-03-25
      相关资源
      最近更新 更多