组合优于继承 - 额外的属性去哪里了? [英] Composition over Inheritance - where do extra properties go?

查看:22
本文介绍了组合优于继承 - 额外的属性去哪里了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从示例 HR 系统中获取以下代码.用户可以记录缺勤,并且可以是各种类型的,包括假期和疾病.这将是一个基于 ORM 的域模型,例如 NHibernate.

Take this following code from an example HR system. The user has the ability to log an absence and can be of various types including holiday and sickness. This would be a domain model over an ORM such as NHibernate.

public class Absence
{
    public long Id {get;set;}
    public Employee Employee {get;set;}
    public DateTime StartDate {get;set;}        
    public DateTime EndDate {get;set;}

    public virtual void DoSomething()
    { ... }
}

public class Holiday : Absence
{ 
    public string Location {get;set;}

    public override void DoSomething()
    { ... }
}

public class Sickness : Absence
{
    public bool DoctorsNoteProvided {get;set;}

    public override void DoSomething()
    { ... }
}

这是一个例子 - 请不要质疑为什么需要位置,假设它是一个规范.

This is an example - please don't question why location would be required, assume it is a specification.

用户想要更改类型 - 他以为该员工生病了,但后来想起那是假期.同样,您可能认为这是一个糟糕的设计,但将其视为一项要求 - 这代表了一个对我来说多次出现的问题.

The user wants to change the type - he thought the employee was off sick but then remembered it was a holiday. Again, you may think this is a bad design but treat it like a requirement - this represents a problem that has come up many times for me.

问题是您无法将对象的类型从 Sickness 更改为 Absence.一般来说,建议是优先组合而不是继承(四人组)并这样做:

The problem is that you cannot change the type of an object from Sickness to Absence. Generally, the advice would be to Favour Composition Over Inheritance (Gang of Four) and do this:

public class Absence
{
    public long Id {get;set;}
    public Employee Employee {get;set;}
    public DateTime StartDate {get;set;}        
    public DateTime EndDate {get;set;}

    public AbsenceType Type {get;set;}

    public void DoSomething()
    {
        Type.DoSomething();
    }
}

但是当我这样做时,特定于 Holiday 和 Sickness 的属性什么时候去(分别为 Location 和 DoctorsNoteProvided)?

But when I do this, when do the properties specific to Holiday and Sickness go (Location and DoctorsNoteProvided respectively)?

推荐答案

为什么需要改变对象的类型?

Why do you need to change the type of an object?

您将拥有某种缺席集合,只需替换有问题的项目即可.

You will have some kind of collection of Absences, just replace the item in question.

可以想象,您甚至可以保留原始请求并将其标记为已取代,而不是替换,这对于审计跟踪目的可能很重要.

Conceivably rather than replacing you even keep the original request and mark it as superceded, that might be important for audit trail purposes.

这篇关于组合优于继承 - 额外的属性去哪里了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆