Home  /  Questions  /  Question

50   50
Jan 19, 2015

access class specific properties with program to interface

Hey there !!
I am trying to design a web portal for auto/car dealer. When customer searches for a vehicle, they can show their "like" and "contact" a sales person for their area.
My client sells different vehicles - cars, two wheeler as of now. While building this I want to make save of data in a generic fashion. So I am thinking of pattern for program to interface rather than concrete class. In this case, I will have a class Vehicle which will implement IVehicle interface which will have some properties as well methods. Vehicle will be base class for Car and Motorcycle. Now when I call method like Save, I would like to pass IVehicle as input rather than Car or Motorcycle as input so that I can access generic properties. However there will also be some specific properties in Car and Motorcycle - like in example below, how would I access those specific properties if I use this pattern of interfaces. Example in code section below.

Please advice.

Interface IVehicle
        Public VehicleType As String()
        Public Color As String()

Class Vehicle Implements IVehicle
        Public VehicleType As String() Implments IVehicle.VehicleType
        Public Color As String() Implments IVehicle.Color

Class Car Inherits Vehicle
        Public Property IsHatchback As Boolean  

Class Motorcycle Inherits Vehicle
        Public Property HasFootPedal As Boolean

Public Sub Save(input As IVehicle)
    If Car then Console.WriteLine(input.IsHatchBack)
    If Motorcycle Console.WriteLine(input.HasFootPedal)
End Sub

This looks like Active Record pattern, you may also want to take a look at Repository pattern for persisting data. If you prefer this approach you may want to make Vehicle abstract and add Save to the Vehicle class as virtual so you can override it if necessary in the classes which need to check properties before saving. --- Paul Hazells  Jan 21, 2015
Thanks Paul for inputs. I am looking into repository pattern. I m though not clear on how to access IsHatchBack property or HasFootPedal. When I do "input.", I only see Color and VehicleType as available properties. Using interface as an input parameter to method,, I cannot access properties that are in derived classes. Am I missing something? --- Tirath G  Jan 24, 2015