c# - 当类型可以是两种不同事物之一时的设计选项

标签 c# oop design-patterns

假设我有一个客户类型,并且我想为所有客户存储某些信息。然而,客户可以是个人也可以是组织。在每种情况下,我都希望在它们上存储不同类型的信息,并能够以不同的方式对它们采取行动。

我通常只想处理 Customer 对象,但在某些时候,根据情况以不同的方式处理更具体的类型(例如,在创建地址时我想使用 Person 的 Surname 和 GiveNames,而是组织的 TradingName(但没有填充 OrgName)。

我不知道如何处理这个问题。我在搜索时找到的示例/问题假设更具体的类型具有相同的属性/方法,因此可以进行一般处理。

我的 Customer 对象中是否只有一个用于任一类型的字段和一个标志来指示哪个类型具有值(即 isPerson()),并在需要时在我的代码中进行检查。我是否使用继承以及在需要时使用 IsType() 类型的逻辑?或者我是否缺少一些有助于解决此类场景的设计模式?

最佳答案

Do I just have a field for either type in my Customer object and a flag to indicate which has a value (i.e., isPerson()) and check that in my code when I need to. Do I use inheritance and when needed use IsType() type of logic?

不,这违背了 polymorphism 的目的.

定义一个接口(interface)来捕获两个类的共同点,以便您可以在适当的时候以相同的方式对待它们。您很有可能还希望创建一个公共(public)基类,该基类至少实现该接口(interface)的一部分,以提供公共(public)行为。您最终可能会将接口(interface)的某些实现保留为抽象方法,这些方法从 Person 和 Organization 子类获取具体实现。

糟糕的设计

public class Customer
{
    public void DoSomethingCustomersDo()
    {
        if (isPerson())
        {
            /* Person implementation */
        }
        else
        {
            /* Organization implementation */
        }
    }
}

更好的设计

public interface ICustomer
{
    void DoSomethingCustomersDo();
}

public abstract class Customer : ICustomer
{
    public string SomeSharedProperty { get; set; }

    public abstract void DoSomethingCustomersDo();
}


public class Person : Customer
{
    public override void DoSomethingCustomersDo()
    {
        /* Person implementation */
    }
}

public class Organization : Customer
{
    public override void DoSomethingCustomersDo()
    {
        /* Organization implementation */
    }
}

关于c# - 当类型可以是两种不同事物之一时的设计选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30043754/

相关文章:

c# - DataGridViewCellStyle.Padding 属性不是填充?

c# - 如何在wpf中的自定义窗口中查找控件

c# - 找不到 PInvoke DLL - BUG?

ios - 在 Swift 中从多个 ViewController 收集数据

c++ - 观察数据变化的不同方式

c# - 制作多语言用户控件

具有子类唯一性和多态性的Java引用类型

python - 向初学者解释 'self' 变量

java - 装饰器模式: Is it required that all decorators add value despite the sequence of initialization

javascript - 如何在 Javascript 中将中介器模式与多个中介器实例一起使用?