是否存在仅属性值的某些排列等于有效对象的反模式的名称?

我不知道该如何用文字来形容。

这就像假设我们有一个类似的层次结构

  • IFoo
    • Foo1
    • Foo2
  • IBar
    • Bar1
    • Bar2
    • Bar3

和类似对象

public class Baz
{
   public IFoo Foo { get; set; }
   public IBar Bar { get; set; }
}

和类似的业务规则

=================================
Foo type | Bar type | Valid Baz?
=================================
| Foo 1  |  Bar 1   |  false   |
---------------------------------
| Foo 1  |  Bar 2   |  false   | 
---------------------------------
| Foo 1  |  Bar 3   |  true    |     
---------------------------------
| Foo 2  |  Bar 1   |  true    | 
---------------------------------
| Foo 2  |  Bar 2   |  true    | 
---------------------------------
| Foo 2  |  Bar 3   |  false   | 

(或者这甚至是反模式吗?)

LVCHA166 回答:是否存在仅属性值的某些排列等于有效对象的反模式的名称?

它看起来不像是反模式。您是在抽象级别描述的,我只能假设Baz仅对IFooIBar接口的某些实现才有意义。在这种情况下,您需要实现额外的类,以保护系统免受“不良” Baz对象的侵害。您可以使用Builder或其他Creational Pattern来创建仅有效的Baz对象。

使用Builder可能看起来像这样:

Baz validBaz = new BazBuilder().withFoo(foo).withBar(bar).build();

您可以验证方法中的实例或创建具有允许类型的方法集:

public BazBuilder withBar(Bar1 bar) { ... }

public BazBuilder withBar(Bar2 bar) { ... }

因此,用户只能提供Bar1Bar2实例。禁止使用Bar3。当然,在这种情况下,Baz类不能以其他方式实例化。

本文链接:https://www.f2er.com/3155801.html

大家都在问