【发布时间】:2019-03-18 19:45:24
【问题描述】:
假设我拥有一项服务并发布了类似的合同
public class MyObject
{
public int Foo { get; }
public string Bar { set; }
}
我认为在数据合同中存在“行为”是不合适的,例如
public class MyObject
{
public int Foo { get; }
public string Bar { set; }
public void DoSomeAlgorithmWithMyProperties() { … }
}
换句话说,数据合约应该只是价值袋。
所以我的问题是如何在这样的对象上创建行为。我可以看到的一种方法是创建一个单独的镜像对象,例如
public class MyObjectInternal
{
public int Foo { get; }
public string Bar { set; }
public class MyObjectInternal(int foo, string bar)
{
this.Foo = foo;
this.Bar = bar;
}
public void DoSomeAlgorithmWithMyProperties() { … }
}
另一个是继承
public class MyObjectInternal : MyObject
{
public class MyObjectInternal(int foo, string bar)
{
this.Foo = foo;
this.Bar = bar;
}
public void DoSomeAlgorithmWithMyProperties() { … }
}
其他可能性可能是通过对值进行操作的单独类来完全分离行为和数据,例如
public static class MyObjectAlgorithmDoer
{
public static void DoSomeAlgorithmWithMyProperties(MyObject myObject) { … }
}
【问题讨论】:
标签: c# .net oop design-patterns