【问题标题】:Can one have a polymorphic factory for types inheriting from an interface?可以为从接口继承的类型创建多态工厂吗?
【发布时间】:2017-05-07 14:59:39
【问题描述】:

遵循 SO 和其他地方的建议,我尝试使用接口实现多态性,如下面的简化示例所示。

type IFace =
   // abstract methods
   abstract member foo: int -> int

type X(i: int) =
    // some code
    interface IFace with
        member this.foo j = i + j

type Y(s: string) =
    // some code
    interface IFace with
        member this.foo j = (int s) + j

type Z(x: float) =
    // some code
    interface IFace with
        member this.foo j = (int x) + j

这些值可以被 X、Y 和 Z 的构造函数使用:

let zX = 1
let zY = "2"
let zZ = 3.0

我想建立一个像这样的多态工厂

let create (str: string) =
    match str with
    | "X" -> X(zX)
    | "Y" -> Y(zY)
    | "Z" -> Z(zZ)
    | _ -> failwith "Something went wrong"

let XObj = create "X"    
let YObj = create "Y"
let ZObj = create "Z"

但是,create 不会编译,因为它会返回不同类型的对象。

另一种选择是将create 中的所有案例向上转换为 System.Object:

let create1 (str: string) =
    match str with
    | "X" -> X(zX) :> System.Object
    | "Y" -> Y(zY) :> System.Object
    | "Z" -> Z(zZ) :> System.Object
    | _ -> failwith "Something went wrong"

然后create1 将编译,但它的返回值(我相信)是无用的,除非向下转换为 X、Y 或 Z。但这再次引发了多态性问题:一般向下转换我需要一个返回值的函数不同的类型。

另一种选择是使用有区别的联合

type ClassDU =
    | XClass of X
    | YClass of Y
    | ZClass of Z

并使用上面定义的函数create。但这不起作用。如果不向上转换,编译器仍然会将不同的情况视为具有不同的类型。由于 ClassDU 不是一个类,因此向上转换到 ClassDU 不起作用。

在这段代码中sn -p

http://fssnip.net/k6/title/-F-Factory-Pattern

使用抽象类 XYZ 解决了这个问题,X、Y 和 Z 将从中继承抽象方法 foo。类似于create 的函数会将所有情况向上转换为抽象类:

let create2 (str: string) =
    match str with
    | "X" -> X(zX) :> XYZ
    | "Y" -> Y(zY) :> XYZ
    | "Z" -> Z(zZ) :> XYZ
    | _ -> failwith "Something went wrong"

是否可以为从接口继承的类型创建多态工厂,还是必须像在代码 sn-p 中那样创建抽象类?

【问题讨论】:

    标签: interface f# polymorphism abstract-class discriminated-union


    【解决方案1】:

    接口

    要对接口执行此操作,您只需向上转换为接口的类型,例如:

    let create (str: string) =
        match str with
        | "X" -> X(zX) :> IFace
        | "Y" -> Y(zY) :> IFace
        | "Z" -> Z(zZ) :> IFace
        | _ -> failwith "Something went wrong"
    

    这有类型签名:

    val create : str:string -> IFace
    

    有区别的工会

    要对 DU 执行此操作,您需要在 create 函数中添加适当的 case 构造函数。

    type ClassDU =
        | XClass of X
        | YClass of Y
        | ZClass of Z
    
    let createDU (str: string) =
        match str with
        | "X" -> XClass <| X(zX) 
        | "Y" -> YClass <| Y(zY)
        | "Z" -> ZClass <| Z(zZ)
        | _ -> failwith "Something went wrong"
    

    这有类型签名:

    val createDU : str:string -> ClassDU
    

    我认为您对受歧视联合的行为的误解源于您将它们视为具有多个子类的抽象类,将它们视为更好更准确具有多个构造函数的单一类型。

    【讨论】:

    • 我听从了你关于接口的建议,当然它奏效了。两个问题。首先,在我使用create 函数构造了我的对象之后,一些向上转换变得不必要了,编译器开始对它们发出警告。我现在处理的对象是否与我在使用常规类构造函数之前创建的对象不同?如果是这样,我会失去一些功能吗?第二:如果我的类从多个接口继承并且create 只向上转换到其中一个接口,会发生什么情况?我可以同时向上转换到多个接口吗?
    猜你喜欢
    • 2010-11-05
    • 2010-10-07
    • 2014-03-05
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    相关资源
    最近更新 更多