Announcement

Collapse
No announcement yet.

Simple Polymorphic List

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Simple Polymorphic List

    Here's a simple example of creating a polymorphic list:
    Zip

    SimplePoly.bas
    Code:
    #Compile Exe
    #Compiler PBWin 10, PBCC 6
    #Dim All
     
    ' Minimalistic example of creating polymorphic lists in PB.
    ' Creates a type safe list of different types of animals
    ' and then listens to each.
     
    Function PBMain () As Long
      Local animal As iAnimal
      Local animals As iAnimals
     
      animals = Class "cAnimals"
      ' Add different types of animals to list
      animal = Class "cDog":  animals.Add( animal )
      animal = Class "cCat":  animals.Add( animal )
      animal = Class "cDuck": animals.Add( animal )
     
      ' Iterate list listening to each
      ? animals.Listen()
    End Function
     
    Class cAnimals
      ' Type safe implementation of an animal list
      Instance animals() As iAnimal
     
      Interface iAnimals
        Inherit IUnknown
        Method Add( animal As iAnimal )
          Local m As Long
          If IsInterface( animal, iAnimal ) = 0 Then Exit Method
          m = UBound( animals() ) + 1
          ReDim Preserve animals( m )
          animals( m ) = animal
        End Method
     
        Method Listen() As String
          Local i, cnt As Long
          Local sounds As String
          cnt = UBound( animals() )
          For i=0 To cnt
            If i Then sounds += ", "
            sounds += animals(i).Speak()
          Next
          Method = sounds
        End Method
      End Interface
    End Class
     
    Class cDog
      Interface iAnimal
        Inherit IUnknown
        Property Get Speak() As String
          Property = "Bark"
        End Property
      End Interface
    End Class
     
    Class cCat
      Interface iAnimal
        Inherit IUnknown
        Property Get Speak() As String
          Property = "Meow"
        End Property
      End Interface
    End Class
     
     
    Class cDuck
      Interface iAnimal
        Inherit IUnknown
        Property Get Speak() As String
          Property = "Quack"
        End Property
      End Interface
    End Class
    Last edited by Larry Charlton; 29 Nov 2014, 08:10 PM. Reason: Added a link to a zip file.
    LarryC
    Website
    Sometimes life's a dream, sometimes it's a scream
Working...
X