可选但必需变量的干净解决方案

Clean solution for optional yet required variables

是否有针对以下情况的某种设计模式?

要求:

目前的情况对我来说有点"dirty",所以我想知道是否有"clean"解决方案。我自己找不到答案。

根据 JP Nizet 的评论,您可以将 Location 实现为不可变对象并提供两个工厂方法:

class Location
{
    private readonly double lat;
    private readonly double lon;
    private readonly string place;
    private readonly string name;

    // Hide the constructor and only allow creation using the factory methods
    // Alternative: Only provide factory method with lat and lon parameters and make this constructor public
    private Location(double lat, double lon, string place, string name)
    {
        this.lat = lat;
        this.lon = lon;
        this.place = place;
        this.name = name;
    }

    // Factory methods
    public static Location Create(double lat, double lon)
    {
        return new Location(lat, lon, lat.ToString(), lon.ToString());
    }

    public static Location Create(double lat, double lon, string place, string name)
    {
        return new Location(lat, lon, place, name);
    }

    public double getLat()
    {
        return this.lat;
    }

    public double getLon()
    {
        return this.lon;
    }

    public string getPlace()
    {
        return this.place;
    }

    public string getName()
    {
        return this.name;
    }
}

现在由用户决定使用什么策略来创建 Location class 的实例。

编辑: 提供的代码仅用于展示两种(隐式)策略的思想。

您可以将可选变量与必需变量分开并使用 多态性以避免 getName()getPlace() 中的空值检查。 可能类似于以下内容:

您需要应用的模式称为约束。只需将两个 <<invariant>> 约束附加到您的 class 告诉

{lat and lon are always required}

{place and/or name are optional (can be null)}

正文

When the optional variables are null, getPlace() and getName() should return the lat and lon as string.

是 class 行为描述的一部分。

附带说明:"should" 意味着如果你是一个好人,你可以实施,但如果你忽视它,你就不会被打败。使用 "shall".

默认情况下,每个 UML 属性 的重数为 1。UML 2.5 规范的第 9.5.4 节说:

<multiplicity-range> is the multiplicity range of the Property. If this term is omitted, it implies a multiplicity of 1 (exactly one).

这意味着,在您的图表中,所有属性(lat、lon、place、name)都是必需的。要指示 属性 是可选的,您可以在 属性 类型之后附加多重性范围 [0..1]

getPlace 和 getName 方法的行为通常不包含在 class 图中。 class 图主要用于指定结构,而不是行为。您可以像您一样添加注释,但就个人而言,我会用纯文本而不是任何图表来描述这种行为。大多数 UML 工具允许您为每个操作编写纯文本描述并生成包含所有这些描述的文档。但这只是一种方法。您也可以使用 Word 或 Wiki。