在使用AbstractFactory-Pattern和多态性的情况下如何实现IXmlSerializable.ReadXml

时间:2019-01-29 15:16:37

标签: vb.net ixmlserializable

我在项目中使用了AbstractFactory和多态性,需要根据父项下的xml元素将xml反序列化为正确的类型。

更具体(一些伪代码进行解释):

Public Interface IAnimal
              Inherits IXmlSerializable

   Public Property Name as String
   Public Property Age as Integer
   Public ReadOnly Property Type as AnimalType 'actually this is en Enum
End Interface

Public Interface IAnimalFactory
   Public Function Breed(animalType as AnimalType) as IAnimal
End Interface

Public Class AnimalFactoryImpl
             Implements IAnimalFactory
   Public Function Breed(animalType as AnimalType) as IAnimal
      Select Case animalType
         case ...
            return new Dog()
      End Select
   End Function
End Class

Public Mustinherit Class AnimalBaseImpl
                         Implement IAnimal
   'do all the general stuff common to all animals here

   Public MustOverride Sub Talk(words As String)

   'implement IXmlSerializable.ReadXml here
   'implement IXmlSerializable.WriteXml here
End Class

Public Class Dog
             Inherits AnimalBaseImpl
   'do dog specifics here
   'implement Talk() here
End Class

Public Class Cat
             Inherits AnimalBaseImpl
   'do cat specifics here
   'implement Talk() here
End Class

Public Class Cow
             Inherits AnimalBaseImpl
   'do cowspecifics here
   'implement Talk() here
End Class

我需要/拥有的xml看起来像他的

<animal>
   <animalType>Dog</animalType>
   <name>Snoopy</name>
   <age>62</age>   
</animal>

实现WriteXml方法很容易。 但是,ReadXml让我头疼。

到目前为止,我已经在父对象(例如Farm)中包含了反序列化代码。我从animal标签中读取了所有元素,然后根据animalType调用animalFactory创建正确的类型。

我认为这确实不是很好的代码,它确实应该进入AnimalBaseImpl或工厂,但是我无所适从,因为新的AnimalBaseImpl()是反序列化时会发生的第一件事...

任何提示和技巧欢迎:-)

1 个答案:

答案 0 :(得分:0)

好的,再考虑了一点之后,我自己想出了解决方案。到达那里就很容易了;-)

由于我使用的是Factory模式,因此需要实现反序列化的是Factory。毕竟,这是一种创造模式。这意味着所有创建方法都应进入该工厂。反序列化是一种创建方法。

我要做的就是将XmlReader对象传递给工厂,并期望返回工厂创建的任何内容。

继续使用上面的代码示例:

Public Interface IAnimalFactory
   Public Function Breed(animalType as AnimalType) as IAnimal
   Public Function XmlDeserializeAnimal(reader As XmlReader) As IAnimal
End Interface

Public Class AnimalFactoryImpl
             Implements IAnimalFactory
   Public Function Breed(animalType as AnimalType) as IAnimal
      Select Case animalType
         case ...
            return new Dog()
      End Select
   End Function

   Public Function XmlDeserializeAnimal(reader As XmlReader) As IAnimal implements IAnimalFactory.XmlDeserializeAnimal
      'read all the tags here inkl. animalType
      Dim returnAnimal as IAnimal = Me.Breed(animalType)
      'set name and age here as per xml
      Return returnAnimal
End Class

现在可以很容易地从容器对象(例如Farm)中调用该对象,该对象也实现了IXmlSerializable。 而且所有容器类需要了解的就是IAnimalFactory和XmlDeserializeAnimal方法。

想想就更直接(^ _〜)