Acme Travel Agency Case Study: Implementation

Team-Fly    

 
Application Development Using Visual Basic and .NET
By Robert J. Oberg, Peter Thorsteinson, Dana L. Wyatt
Table of Contents
Chapter 5.  Inheritance and Exceptions in VB.NET


With the abstractions Reservable , Reservation , and Broker already in place, it now becomes very easy to implement a reservation system for a particular kind of reservable, such as a Hotel . Figure 5-2 illustrates our inheritance hierarchy. Hotel derives from Reservable , HotelReservation derives from Reservation , and HotelBroker derives from Broker .

Figure 5-2. Class hierarchy for Acme hotel reservation system.

graphics/05fig02.gif

In this section we will examine key pieces of the implementation of the case study, which is in the CaseStudy folder for this chapter.

Running the Case Study

Before proceeding with our code walkthrough, it would be a good idea to build and run the case study. The program TestBroker.exe is a console application. By typing "help" at the command prompt, you can obtain a list of commands:

 graphics/codeexample.gif Enter command, quit to exit H> help The following commands are available:    hotels    shows all hotels in a city    all       shows all hotels    cities    shows all cities    add       adds a hotel    book      book a reservation    bookings  show all bookings    register  register a customer    email     change email address    show      show customers    quit      exit the program H> 

Experiment with this program until you have a clear understanding of its various features.

HotelReservation

HotelReservation is a simple class derived from Reservation . The code is in the file hotelbroker.vb . It adds some additional public fields and provides the property ArrivalDate as a more meaningful wrapper around the generic DateTime field of the base class.

 Public Class HotelReservation    Inherits Reservation    Public CustomerId As Integer    Public HotelName As String    Public City As String    Public DepartureDate As DateTime    Public Property ArrivalDate() As DateTime       Get          ArrivalDate = DateTime       End Get       Set(ByVal Value As DateTime)          DateTime = Value       End Set    End Property End Class 

HotelBroker

The heart of the implementation is the HotelBroker class, derived from Broker . The code is also in the file hotelbroker.vb .

 Public Class HotelBroker    Inherits Broker    Private Const m_MAXDAY As Integer = 366    Private Const m_MAXUNIT As Integer = 10    Private Const m_MAXCITY As Integer = 5    Private Shared m_nextCity As Integer = 0    Private m_cities() As String    Public Sub New()       MyBase.New(m_MAXDAY, m_MAXUNIT)       m_cities = New String(m_MAXCITY) {}       AddHotel("Atlanta", "Dixie", 100, 115D)       AddHotel("Atlanta", "Marriot", 500, 70D)       AddHotel("Boston", "Sheraton", 250, 95D)    End Sub    ... 

There are constants for various array definitions and a new array to hold the cities. The constructor passes some array definitions to the base class, initializes the m_cities array, and adds some starter hotels as test data.

The next part of the code defines a NumberCity property and provides a method to add a hotel.

 Public ReadOnly Property NumberCity() As Integer      Get          Return m_nextCity      End Get End Property Public Function AddHotel(_  ByRef city As String, _  ByRef name As String, _  ByVal number As Integer, _  ByVal cost As Decimal) As String    If FindId(city, name) <> -1 Then       Return "Hotel is already on the list"    End If    Dim hotel As Hotel = New Hotel(_       city, name, number, cost)    AddUnit(hotel)    AddCity(city)    Return "OK" End Function ... 

Private helper functions are provided to find the ID of a hotel and to add a city to the list of cities. A city can be added only if it is not already on the list; duplicates are not permitted.

 Private Function  FindId  (_  ByRef city As String, _  ByRef name As String) As Integer    Dim i As Integer    For i = 0 To NumberUnits - 1       Dim hotel As Hotel = m_units(i)       If hotel.City = city And _        hotel.HotelName = name Then          Return hotel.HotelId       End If    Next    Return -1 End Function Private Sub  AddCity  (ByRef city As String)    ' check if city already on list, add if not    If (Not Contains(city)) Then        m_cities(m_nextCity) = city        m_nextCity += 1    End If End Sub Private Function  Contains  (ByRef city As String) _  As Boolean    Dim i As Integer    For i = 0 To NumberCity - 1       If (m_cities(i) = city) Then          Return True       End If    Next    Return False End Function 

Methods are provided to show all the hotels, all the hotels in a given city, and to show the cities. You may wish to examine these methods in the solution provided, for a review of formatting in VB.NET. We do not show these methods here.

We finally come to the key method Reserve , which is used to book a hotel reservation.

 Public Overloads Function  Reserve  (_  ByVal customerId As Integer, _  ByRef city As String, _  ByRef name As String, _  ByVal dt As DateTime, _  ByVal numDays As Integer) As ReservationResult    Dim id As Integer = FindId(city, name)    If id = -1 Then       Dim result As ReservationResult = _          New ReservationResult()       result.ReservationId = -1       result.Comment = "Hotel not found"       Return result     End If     Dim res As HotelReservation = _        New HotelReservation()     res.UnitId = id     res.CustomerId = customerId     res.HotelName = name     res.City = city     res.ArrivalDate = dt  res.DepartureDate = dt.Add(_   New TimeSpan(numDays, 0, 0, 0))  res.NumberDays = numDays  Return Reserve(res)  End Function 

The code in this class is very simple, because it relies upon logic in the base class Broker . An error is returned if the hotel cannot be found on the list of hotels. Then a HotelReservation object is created, which is passed to the Reserve method of the base class. (Note use of the Overloads keyword, and the fact that the base class Reserve has a different signature than the Reserve method in the derived class.) We create the reservation object in the derived class because we are interested in all the fields of the derived HotelReservation class, not just the fields of the base Reservation class. We have previously used the DateTime structure, and we now use the TimeSpan structure in calculating the departure date by adding the number of days of the stay to the arrival date. This calculation relies on the fact that the Add method is provided by the DateTime structure.

Customers

No reservation system can exist without modeling the customers that use it. The Customers class in the file customer.vb maintains a list of Customer objects. Again we use an array as our representation. This code has very similar structure to code dealing with hotels, and so we show it only in outline form, giving the data structures and the declarations of the public methods and properties.

 ' Customer.vb Imports System Namespace OI.NetVb.Acme    Public Class Customer       Public CustomerId As Integer       Public FirstName As String       Public LastName As String       Public EmailAddress As String       Private Shared m_nextCustId As Integer = 1       Public Sub New(_        ByRef first As String, _        ByRef last As String, _        ByRef email As String)          CustomerId = m_nextCustId          m_nextCustId += 1          FirstName = first          LastName = last          EmailAddress = email        End Sub     End Class    Public Class Customers       Private m_customers As Customer()       Private Shared m_nextCust As Integer = 0       Public Sub New(ByVal MaxCust As Integer)          m_customers = New Customer(MaxCust) {}          RegisterCustomer(_             "Rocket", _             "Squirrel", _             "rocky@frosbitefalls.com")          RegisterCustomer(_             "Bullwinkle", _             "Moose", _             "moose@wossamotta.edu")       End Sub       Public ReadOnly Property NumberCustomers(...       ...       Public Function RegisterCustomer(...       ...       Private Sub Add(ByRef cust As Customer)       ...       Public Sub ShowCustomers(...       ...       Private Function FindIndex(...       ...       Public Sub ChangeEmailAddress(...       ...    End Class End Namespace 

Namespace

All case study code is in the namespace OI.NetVb.Acme . All of the files defining classes begin with a Namespace directive. There is a corresponding Imports directive, which you will see in the file TestHotel.vb . [5]

[5] If you look at the properties for the project, you will see that we have made the "Root namespace" blank. If we had not done so, the actual namespace would have been TestHotel.OI.NetVb.Acme .

 ' Customer.vb Imports System Namespace OI.NetVb.Acme ... 

TestHotel

The TestHotel class in the file TestHotel.vb contains an interactive program to exercise the Hotel and Customer classes supporting the commands shown previously, where we suggested running the case study. There is a command loop to read in a command and then exercise it. There is a big Try block around all the commands with a Catch handler afterward. (We discuss exception handling with TryCatch later in the chapter.) Note the Imports statements to gain access to the namespaces.

 ' TestHotel.vb Imports System  Imports OI.NetVb.Acme  Module TestHotel    Sub Main()       Const MAXCUST As Integer = 10  Dim hotelBroker As HotelBroker = New HotelBroker()   Dim customers As Customers = New Customers(MAXCUST)  Dim iw As InputWrapper = New InputWrapper()       Dim cmd As String       Console.WriteLine("Enter command, quit to exit")       cmd = iw.getString("H> ")       While Not cmd.Equals("quit")          Try             If (cmd.Equals("hotels")) Then                Dim city As String = _                   iw.getString("city: ")                hotelBroker.ShowHotels(city)             ElseIf (cmd.Equals("all")) Then                 hotelBroker.ShowHotels()             ElseIf (cmd.Equals("cities")) Then                ...             Else                hotelhelp()             End If          Catch e As Exception             Console.WriteLine(_                "Exception: {0}", e.Message)          End Try          cmd = iw.getString("H> ")       End While    End Sub    Private Function hotelhelp()       Console.WriteLine(_          "The following commands are available:")       ...    End Function End Module 

Team-Fly    
Top
 


Application Development Using Visual BasicR and .NET
Application Development Using Visual BasicR and .NET
ISBN: N/A
EAN: N/A
Year: 2002
Pages: 190

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net