【问题标题】:Accessing container properties from child list从子列表访问容器属性
【发布时间】:2014-08-18 08:17:30
【问题描述】:

我有一个名为 PaymentPlan 的容器类,它包含基本的付款摘要信息。它还包含一个 ExpectedPayments 列表。希望是一个相当基本的 OOP 类型问题,我的大脑似乎已经进入睡眠状态 - 我在 ExpectedPayment 类中有一个属性,它需要询问 PaymentPlan 类上的一个属性以确定结果。

我目前正在将 PaymentPlan 的引用存储为 ExpectedPayment 类的属性,但是,它有一个公共 getter,在 DDD 之后,我觉得这有点代码味道。有没有更好的方法来实现我想要的?

作为示例,我已经删除了所有必要的部分:

public class PaymentPlan
{
    private readonly List<ExpectedPayment> _payments;

    public PaymentPlan(List<ExpectedPayment> payments)
    {
        ... Other Stuff

        //TODO: Fix this smell
        _payments = payments;
        _payments.ForEach(p => p.Plan = this);
    }

    ... Other Properties
}

还有 ExpectedPayment 类:

public class ExpectedPayment
{
    public ExpectedPayment(... Args removed for example)
    {
    }

    //TODO: Attempting to avoid this public setter as I have no control..
    public PaymentPlan Plan { get; set; }

    public PaymentState PaymentState
    {
        get
        {
            if (Plan.SomePropertyOnPlan == "SomeValue")
            {
                return PaymentState.SomeState;
            }
            else 
            {
                ... Other logic to determine the payment state of this expected payment.
            }
        }
    }

    ... Other Properties

}

任何帮助表示赞赏! - 如果可能的话,我想知道一些技术,因为知道有多种方法可以实现我所追求的目标。

谢谢, 亚历克斯

【问题讨论】:

  • 在您的业务逻辑中,ExpectedPayment 可以没有任何 PaymentPlan 吗?
  • ExpectedPayments 链接到 1 个计划。 PaymentPlan 和 ExpectedPayment 之间存在 1 - many,ExpectedPayments 不能与任何其他计划关联。 (可能我的代码中有另一种味道?)

标签: c# oop properties domain-driven-design parent-child


【解决方案1】:

如果ExpectedPayment 不存在任何PaymentPlan,就好像它不应该存在一样,你必须强制你的ExpectedPayment() 构造函数向调用者提供PaymentPlan 并添加一个“友好”方法来添加新的ExpectedPlanPaymentPlan 上。

public class ExpectedPayment
{
    public ExpectedPayment(PaymentPlan plan, ..... other args)
    {
        Plan = plan ; 
        plan.AddExpectedPlan(this) ; 
        ......
    }

    ......

....

public class PaymentPlan 
{
    .........

    internal void AddExpectedPlan(ExpectedPlan expectedPlan) 
    { 
        ...........
        _payments.Add(expectedPlan) ; 
    } 
}

【讨论】:

  • 啊,是的,我明白了,这更有意义!非常感谢!我会试一试。
猜你喜欢
  • 2016-02-24
  • 2011-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 2013-03-24
相关资源
最近更新 更多