【问题标题】:Recommended way to store and retrieve objects with inheritance使用继承存储和检索对象的推荐方法
【发布时间】:2018-06-06 14:21:17
【问题描述】:

在 Neo4j 中存储和检索从其他对象继承属性的对象的推荐方法是什么?

模型如下所示:

public class Base
{
    public string BaseProperty { get; set; }
}

public class DerivedA : Base
{
    public string DerivedAProperty{ get; set; }
}

public class DerivedB : Base
{
    public string DerivedBProperty{ get; set; }
}

我们有很多衍生模型。我们的第一个解决方案是为每个派生类型创建一个事务,其中还包括来自 Base 的属性。问题:每当 Base 发生变化时,我们都必须更改所有派生类型的所有事务。

下一个解决方案是为 Base 编写一个单独的 Transaction,它首先将其属性存储到 neo4j 中。然后在确定了哪个派生类型之后,将创建另一个事务来存储派生类型的剩余属性。这样一来,交易数量翻了一番,但我们有一个清晰的分离,使更改更容易。

检索更加困难。如果我们想要获取存储在 Neo4j 中的所有 DerivedA 类型,我们首先有一个检索基本属性的事务。然后我们确定派生类型并跟进一个从派生类型检索属性的新事务。现在我们必须以正确的方式将两个事务的结果混合在一起,以获得包含所有属性的完整 derivedA 列表。

有没有更简单/更好的方法?

【问题讨论】:

    标签: neo4j


    【解决方案1】:

    尽管您的问题很广泛,但继承还有另一种选择。如果这是您的问题,我认为这是一个有效的问题。

    继承的另一种选择是(例如)装饰器模式:

    核心原则(从head-first设计模式中获取):

    装饰器模式的关键点在于它是继承的替代方案,具有在运行时更改和扩展行为的相同能力,并且不依赖于具有特定版本或其他依赖项的某些基类。

    一个例子,来自这个答案here

    更多关于wikipedia的主题

    我会修改它以使其更具代表性。

    public interface IStudent //this would rather be called an IInformationDisplayer
    {
         string DisplayInformation();
    }
    
    public class Student : IStudent
    {
        public string Name, Grade, Age, etc... { get; set; }
        private IStudent _student = null;
    
        public Student() { }
        public Student(IStudent student) {  _student = student; }
    
        public string DisplayInformation()
        {
            return $"{_student?.DisplayInformation()}" + 
                   $"{Name} - {Age} years old is in {Grade} grade";
        }
    }
    
    public class ScienceStudent : IStudent //it's still a decorator
    {
        public string Labs { get; set; }
        private IStudent _student;
        public ScienceStudentDecorator(IStudent student)
        {
            _student = student;
        }
    
        public string DisplayInformation()
        {
            var info =  _student?.DisplayInformation();
            return $"{info}. Labse are {Labs}";
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-27
      • 1970-01-01
      • 2012-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多