tp 3 - clases (ej. 10 - 21)

36
Trabajo Practico Número 3 Resolución de ejercicios 10 al 21 Programación Orientada a Objetos. UAI Cede Centro. Alejandro Freccero 10/05/2010

Upload: pabloniro

Post on 17-Aug-2015

228 views

Category:

Documents


1 download

DESCRIPTION

qwe

TRANSCRIPT

Trabajo Practico Nmero 3 Resolucin de ejercicios 10 al 21 Programacin Orientada a Objetos. UAI Cede Centro. Alejandro Freccero 10/05/2010 Hoja 1Alejandro Freccero CONTENIDO Ejercicio 10 ................................................................................................................................................... 3 Form1.vb .................................................................................................................................................. 3 Calculadora.vb.......................................................................................................................................... 4 NumeroNegativoException.vb ................................................................................................................. 5 Print Screen .............................................................................................................................................. 5 Ejercicio 11 ................................................................................................................................................... 6 Service.vb ................................................................................................................................................. 6 Ejercicio 12 ................................................................................................................................................... 6 Form1.vb .................................................................................................................................................. 6 Persona.vb ............................................................................................................................................... 8 Persistencia.vb ......................................................................................................................................... 9 Rectangulo.vb ........................................................................................................................................ 10 Class Diagram ......................................................................................................................................... 11 Print Screen ............................................................................................................................................ 11 Ejercicio 13 ................................................................................................................................................. 11 Form1.vb ................................................................................................................................................ 11 Profesional.vb ........................................................................................................................................ 12 Equipo.vb ............................................................................................................................................... 13 Jugador.vb .............................................................................................................................................. 13 Class Diagram ......................................................................................................................................... 15 Print Screen ............................................................................................................................................ 15 Ejercicio 14 ................................................................................................................................................. 15 Form1.vb ................................................................................................................................................ 15 Ejercicio 15 ................................................................................................................................................. 17 Form1.vb ................................................................................................................................................ 17 cOMPUTADORA.vb ................................................................................................................................ 17 Class Diagram ......................................................................................................................................... 18 Ejercicio 16 ................................................................................................................................................. 18 Form1.vb ................................................................................................................................................ 18 tEMA.vb.................................................................................................................................................. 19 eMPLEADOpERMANENTE.vb ................................................................................................................. 20 eMPLEADOcONTRATADO.vb .................................................................................................................. 20 eMPLEADO.vb ........................................................................................................................................ 20 Class Diagram ......................................................................................................................................... 22 Print Screen ............................................................................................................................................ 22 Ejercicio 17 ................................................................................................................................................. 22 Form1.vb ................................................................................................................................................ 22 aLUMNO.vb ............................................................................................................................................ 23 pROFESOR.vb ......................................................................................................................................... 24 Hoja 2Alejandro Freccero pERSONA.vb ........................................................................................................................................... 24 IPROFESOR.vb ........................................................................................................................................ 25 aYUDANTE.vb ......................................................................................................................................... 25 Class Diagram ......................................................................................................................................... 25 Print Screen ............................................................................................................................................ 26 Ejercicio 18 ................................................................................................................................................. 26 Form1.vb ................................................................................................................................................ 26 iVALIDABLE.vb ........................................................................................................................................ 26 aNIMAL.vb .............................................................................................................................................. 26 pERSONA.vb ........................................................................................................................................... 27 Class Diagram ......................................................................................................................................... 28 Print Screen ............................................................................................................................................ 29 Ejercicio 19 ................................................................................................................................................. 29 Form1.vb ................................................................................................................................................ 29 iVALIDABLE.vb ........................................................................................................................................ 29 cUSTOMlISTeNUMERATOR.vb ............................................................................................................... 29 cUSTOMlIST.vb ....................................................................................................................................... 30 Class Diagram ......................................................................................................................................... 30 Print Screen ............................................................................................................................................ 30 Ejercicio 20 ................................................................................................................................................. 30 Form1.vb ................................................................................................................................................ 31 aUTO.vb ................................................................................................................................................. 31 Class Diagram ......................................................................................................................................... 32 Print Screen ............................................................................................................................................ 33 Hoja 3Alejandro Freccero EJERCICIO 10 FORM1.VB Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load TextBox1.Text = String.Empty TextBox2.Text = String.Empty Label1.Text = String.Empty End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click If TextBox1.Text String.Empty And TextBox2.Text String.Empty Then Dim s As Calculadora = New Calculadora Try s.Valor1 = Convert.ToInt32(TextBox1.Text) s.Valor2 = Convert.ToInt32(TextBox2.Text) Catch Ex As NumeroNegativoException MsgBox("No se pueden Operar Numeros Negativos", MsgBoxStyle.Information, "Error") End Try Label1.Text = Convert.ToString(s.Suma()) TextBox1.Text = Label1.Text End If End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click If TextBox1.Text String.Empty And TextBox2.Text String.Empty Then Dim s As Calculadora = New Calculadora Try s.Valor1 = Convert.ToInt32(TextBox1.Text) s.Valor2 = Convert.ToInt32(TextBox2.Text) Catch Ex As NumeroNegativoException MsgBox("No se pueden Operar Numeros Negativos", MsgBoxStyle.Information, "Error") End Try Label1.Text = Convert.ToString(s.Resta()) TextBox1.Text = Label1.Text End If End Sub Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click If TextBox1.Text String.Empty And TextBox2.Text String.Empty Then Dim s As Calculadora = New Calculadora Try s.Valor1 = Convert.ToInt32(TextBox1.Text) s.Valor2 = Convert.ToInt32(TextBox2.Text) Catch Ex As NumeroNegativoException MsgBox("No se pueden Operar Numeros Negativos", MsgBoxStyle.Information, "Error") End Try Hoja 4Alejandro Freccero Label1.Text = Convert.ToString(s.Producto()) TextBox1.Text = Label1.Text End If End Sub Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click If TextBox1.Text String.Empty And TextBox2.Text String.Empty Then Dim s As Calculadora = New Calculadora Try s.Valor1 = Convert.ToInt32(TextBox1.Text) s.Valor2 = Convert.ToInt32(TextBox2.Text) Catch Ex As NumeroNegativoException MsgBox("No se pueden Operar Numeros Negativos", MsgBoxStyle.Information, "Error") End Try Label1.Text = Convert.ToString(s.Division()) TextBox1.Text = Label1.Text End If End Sub End Class CALCULADORA.VB Public Class Calculadora Private _valor1 As Integer Public Property Valor1() As Integer Get Return _valor1 End Get Set(ByVal value As Integer) _valor1 = value If _valor1 < 0 Then Throw New NumeroNegativoException End If End Set End Property Private _valor2 As Integer Public Property Valor2() As Integer Get Return _valor2 End Get Set(ByVal value As Integer) _valor2 = value If _valor2 < 0 Then Throw New NumeroNegativoException End If End Set End Property Public Function Suma() As Integer Dim result As Integer = 0 result = Valor1 + Valor2 Return result End Function Public Function Resta() As Integer Dim result As Integer = 0 result = Valor1 - Valor2 Return result End Function Hoja 5Alejandro Freccero Public Function Producto() As Integer Dim result As Integer = 0 result = Valor1 * Valor2 Return result End Function Public Function Division() As Integer Dim result As Integer = 0 Try result = Valor1 / Valor2 Catch Ex As OverflowException MsgBox("No se puede dividir por cero!", MsgBoxStyle.Exclamation, "error") End Try Return result End Function End Class NUMERONEGATIVOEXCEPTION.VB Public Class NumeroNegativoException Inherits Exception End Class PRINT SCREEN

Hoja 6Alejandro Freccero EJERCICIO11 SERVICE.VB 'namespaces necesarios para la utilizacion de servicios web Imports System.Web.Services Imports System.Web.Services.Protocols Imports System.ComponentModel _ _ _ Public Class service1 Inherits System.Web.Services.WebService 'notar que se utiliza el atributo webmethod para'indicar que el metodo estara disponible como servicio _ Public Function helloworld() As String Return "hello World" End Function _ Public Function OrdenarArray(ByVal arr As String()) As Array 'utilizo la clase array que contiene un metodo Shared 'que me permite facilmente ordenar un arreglo Array.Sort(arr) Return arr End Function _ Public Function generarArray(ByVal cantidadElementos As Integer) As Array 'defino un vector de strings que tiene la cantidad de elementos indicados ' como parametro Dim arr As String() = New String(cantidadElementos) {} 'invoco ramdomize() para que inicialice la gestion de numeros al azar Randomize() 'por cada elemento que tengo dentro del arreglo ... For i As Integer = arr.GetLowerBound(0) To arr.GetUpperBound(0) Dim cadena As String = String.Empty For j As Integer = 0 To 5 cadena += generarCaracter() Next 'asigno una cadena de texto al azar arr(i) = cadena Next Return arr End Function End ClassEJERCICIO12 FORM1.VB ' espacios de nombres a utilizar Imports System.Collections Imports System.Runtime.Serialization.Formatters.Binary Imports System.IO Hoja 7Alejandro Freccero Public Class Form1 'Nombre del archivo donde voy a guardar mis objetos. Const archivo = "c:\temp\prueba.dat" 'Una coleccion que va a contener a todos mis objetos. Dim lista As IList = New ArrayList() Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'iniciando interfaz grafica Label1.Text = "Nombre" Label2.Text = "Apellido" Label3.Text = "Telefono" Button1.Text = "Agregar a la agenda" Button2.Text = "Guardar en " & archivo Button3.Text = "Cargar de " & archivo Button4.Text = "Eliminar de la lista" TextBox1.MaxLength = 10 TextBox2.MaxLength = 10 TextBox3.MaxLength = 10 ListBox1.Font = New Font("courier New", 8) End Sub 'Agrego un objeto a la lista Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'instancio a una persona Dim p As Persona = New Persona(TextBox1.Text, TextBox2.Text, TextBox3.Text) If p.estacompleto Then lista.Add(p) 'agrego 'limpio casillas de texto TextBox1.Text = String.Empty TextBox2.Text = String.Empty TextBox3.Text = String.Empty refrescarLista() Else MessageBox.Show("Por favor, complete todos los campos") End If End Sub 'Guardo mi lista en un archivo Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim persistir As New persistencia(archivo) persistir.guardar(lista) End Sub 'recupero mi lista de un archivo Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click If File.Exists(archivo) Then Dim persistir As New persistencia(archivo) lista = persistir.cargar() refrescarlista() Else MessageBox.Show("No se puede encontrar: " & archivo) End If End Sub 'remuevo de mi lista un objeto Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click Hoja 8Alejandro Freccero 'si se selecciona algun renglon de la listbox... If (ListBox1.SelectedIndex -1) Then 'remuevo el item que se encuentra dentro de mi lista 'en la misma posicion que la de la listbox seleccionada. lista.RemoveAt(ListBox1.SelectedIndex) refrescarlista() End If End Sub 'actualiza un listbox en base al contenido de mi lista Private Sub refrescarlista() 'borro todos los items de la listbox ListBox1.Items.Clear() 'por cada item de mi lista... For Each p As Object In lista ' agregar su representacion como string en la listbox ListBox1.Items.Add(p.ToString()) Next End Sub End Class PERSONA.VB 'utilizo un atributo del framework .net para indicar que mi clase se'puede convertir en una cadena de bits. Public Class Persona #Region "Nombre" Private _nombre As String = String.Empty Public Property Nombre() As String Get Return _nombre End Get Set(ByVal value As String) _nombre = value End Set End Property #End Region #Region "Apellido" Private _apellido As String = String.Empty Public Property Apellido() As String Get Return _apellido End Get Set(ByVal value As String) _apellido = value End Set End Property #End Region #Region "Telefono" Private _telefono As String = String.Empty Public Property Telefono() As String Get Return _telefono End Get Set(ByVal value As String) _telefono = value End Set End Property #End Region Hoja 9Alejandro Freccero Public Sub New() End Sub Public Sub New(ByVal _nombre As String, ByVal _apellido As String, ByVal _telefono As String) Me.Nombre = _nombre Me.Apellido = _apellido Me.Telefono = _telefono End Sub 'sobre escribo el metodo toString() para indicar como se debe mostrar mi objeto ' dentro de un listbox Public Overrides Function ToString() As String Return String.Format("{0} {1} {2}", Me.Apellido.PadRight(10) _ , Me.Nombre.PadRight(10), Me.Telefono.PadRight(10)) End Function Public Function EstaCompleto() As Boolean If Me.Nombre = String.Empty Or Me.Apellido = String.Empty Or Me.Telefono = String.Empty Then Return False End If Return True End Function End Class PERSISTENCIA.VB Imports system.IO Imports System.Runtime.Serialization.Formatters.Binary Public Class Persistencia Dim archivo As String 'bf se encargara de convertir mi lista en una cadena binaria 'como asi tambien de devolverme una lista a partir de otra cadena binaria Dim bf As BinaryFormatter = New BinaryFormatter() Public Sub New(ByVal nombre_archivo As String) Me.archivo = nombre_archivo End Sub Public Sub Guardar(ByVal o As Object) 'creo el archivo donde voy a crear el objeto Dim fs As FileStream = New FileStream(Me.archivo, FileMode.OpenOrCreate) 'transformo una instancia en una cadena de caracteres binarios 'y lo guardo en el archivo indicado bf.Serialize(fs, o) 'cierro el archivo fs.Close() End Sub Public Function cargar() As Object 'abro el archivo donde voy a objeter un objeto Dim fs As FileStream = New FileStream(Me.archivo, FileMode.Open) 'transformo el binario del archivo en una instancia Dim o As Object = bf.Deserialize(fs) 'cierro el archivo fs.Close() Return o End Function Hoja 10Alejandro Freccero End Class RECTANGULO.VB Public Class Rectangulo Private _base As Double Private _altura As Double Property base() Get Return _base End Get Set(ByVal value) _base = value End Set End Property Property altura() Get Return _altura End Get Set(ByVal value) _altura = value End Set End Property Public Function Superficie() As Double Dim Sup As Double Sup = _base * _altura Return Sup End Function End Class Hoja 11Alejandro Freccero CLASS DIAGRAM PRINTSCREEN EJERCICIO13 FORM1.VB Public Class Form1 Dim Lista As List(Of Equipo) = New List(Of Equipo) Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Label14.Text = String.Empty End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim team As Equipo = New Equipo team.Nombre = TextBox25.Text team.Color = TextBox26.Text Hoja 12Alejandro Freccero Lista.Add(team) End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim jugador As Jugador If ComboBox1.Text = "Profesional" Then jugador = New Profesional Else jugador = New Principiante End If jugador.Nombre = TextBox1.Text jugador.CantidadAmarillas = TextBox3.Text jugador.CantidadRojas = TextBox2.Text jugador.GolesRealizados = TextBox4.Text Dim i As Integer = -1 Dim temp As Equipo For Each temp In Lista i = i + 1 Next Dim a As Equipo = New Equipo Lista.Item(i).ListaJugadores.Add(jugador) End Sub Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click Dim MaxPtje As Integer = 0 Dim MaxNomb As String = String.Empty Dim equipo As Equipo = New Equipo For Each equipo In Lista If equipo.ObtenerPuntajeEquipo() > MaxPtje Then MaxNomb = equipo.Nombre MaxPtje = equipo.ObtenerPuntajeEquipo End If Next Label14.Text = "El puntaje Maximo fue del equipo " + MaxNomb + " : " + Convert.ToString(MaxPtje) End Sub End Class PROFESIONAL.VB Public Class Profesional Inherits Jugador Public Overrides Function ObtenerPuntaje() As Integer Dim puntaje As Integer = 0 puntaje = 20 * Me.GolesRealizados - 4 * Me.CantidadRojas - 2 * Me.CantidadAmarillas Return puntaje End Function Function Profesional() As Integer Return 0 End Function Hoja 13Alejandro Freccero End Class EQUIPO.VB Public Class Equipo Private _color As String Public Property Color() As String Get Return _color End Get Set(ByVal value As String) _color = value End Set End Property Private _nombre As String Public Property Nombre() As String Get Return _nombre End Get Set(ByVal value As String) _nombre = value End Set End Property Private _listaJugadores As List(Of Jugador) = New List(Of Jugador) Public Property ListaJugadores() As List(Of Jugador) Get Return _listaJugadores End Get Set(ByVal value As List(Of Jugador)) _listaJugadores = value End Set End Property Function Equipo() As Integer Return 0 End Function Function ObtenerPuntajeEquipo() As Integer Dim ptos As Integer = 0 Dim jugador As Jugador For Each jugador In ListaJugadores ptos = jugador.ObtenerPuntaje + ptos Next Return ptos End Function End Class JUGADOR.VB Public MustInherit Class Jugador Private _cantidadAmarillas As Integer Public Property CantidadAmarillas() As Integer Get Hoja 14Alejandro Freccero Return _cantidadAmarillas End Get Set(ByVal value As Integer) _cantidadAmarillas = value End Set End Property Private _cantidadRojas As Integer Public Property CantidadRojas() As Integer Get Return _cantidadRojas End Get Set(ByVal value As Integer) _cantidadRojas = value End Set End Property Private _golesRealizados As Integer Public Property GolesRealizados() As Integer Get Return _golesRealizados End Get Set(ByVal value As Integer) _golesRealizados = value End Set End Property Private _nombre As String Public Property Nombre() As String Get Return _nombre End Get Set(ByVal value As String) _nombre = value End Set End Property Function Jugador() As String Return 0 End Function MustOverride Function ObtenerPuntaje() As Integer End Class Hoja 15Alejandro Freccero CLASS DIAGRAM PRINT SCREEN

EJERCICIO14 FORM1.VB Module InOut32Module Public Declare Function Inp Lib "input32.dll" () _ alias "inp32" (byval PortAddress as Short) as short Public Declare Sub out Lib "input32.dll" Alias _ "out32" (ByVal portaddress As Short, ByVal value As Short) End Module Public Class Form1 Private Sub TestInput_load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Me.cmbPortOut.Items.add("Salida") Me.cmbPortOut.Items.add("Control") Me.cmbPortOut.items.add("Salida") Me.cmbPortOut.items.add("Entrada") Me.cmbPortOut.items.add("Control") End Sub Private Sub button3_click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button3.click Hoja 16Alejandro Freccero Dim i As Integer = 0 For k As Integer = -1 To 8 If (k = -1) Then i = 0 Else i = Math.Pow(2, k) End If out(&H378S, CType(i, Short)) System.Threading.Thread.Sleep(50) Console.WriteLine(i) Next For k As Integer = 8 To -1 Step -1 If (k = -1) Then i = 0 Else i = Math.Pow(2, k) End If out(&H378S, CType(i, Short)) System.Threading.Thread.Sleep(50) Console.WriteLine(i) Next End Sub Private Sub button4_click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button4.click Dim i As Integer = 0 For k As Integer = -1 To 6 If (k = -1) Then i = 0 Else i = Math.Pow(2, k) + Math.Pow(2, k + 1) End If out(&H378S, CType(i, Short)) Console.WriteLine(i) System.Threading.Thread.Sleep(50) Next For k As Integer = 7 To -1 Step -1 If (k = -1) Then i = 0 Else i = Math.Pow(2, k) + Math.Pow(2, k - 1) End If out(&H378S, CType(i, Short)) System.Threading.Thread.Sleep(50) Console.WriteLine(i) Next End Sub Private Sub button1_click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.click out(&H378S, CType(txtvalorout.text, Short)) End Sub Private Sub button2_click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button2.click txtvalorin.text = Inp(&H378S) End Sub Private Sub button5_click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button5.click For k As Integer = 0 To 255 out(&H378S, CType(k, Short)) System.Threading.Thread.Sleep(50) Next For k As Integer = 255 To 0 Step -1 Hoja 17Alejandro Freccero out(&H378S, CType(k, Short)) System.Threading.Thread.Sleep(50) Next End Sub Private Sub button6_click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button6.click Dim r As Integer For k As Integer = 0 To 255 r = Math.Round(Rnd() * 255) out(&H378S, CType(, Short)) System.Threading.Thread.Sleep(50) Next End Sub End Class EJERCICIO15 FORM1.VB Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load End Sub End Class COMPUTADORA.VB Public Class Computadora 'declaro el evento "onrecibiendo datos" "se declara del tipo del delegado!!!!!!!!!!!!" 'declaro el delegado "transmisiondedatoseventhandler" y una firma de 2 strings 'el raisevent o llamado al evento debe devolver 2 strings!!!!! Private Event onRecibiendoDatos As TransmisionDatosEventHandler Private Delegate Sub TransmisionDatosEventHandler(ByVal ComputadoraOrigen As String, ByVal Datos As String) Private _nombre As String Public Overridable Property Nombre() As String Get Return _nombre End Get Set(ByVal value As String) _nombre = value End Set End Property Public Sub New(ByVal _nombre As String) Me.nombre = _nombre End Sub Public Sub Enviar(ByVal Datos As String) RaiseEvent onRecibiendoDatos(Me.Nombre, Datos) End Sub 'mando por parametro la compu1 y a traves del addhandler digo q la que maneja el evento es Public Sub SuscribirmeA(ByVal OtraComputadora As Computadora) AddHandler OtraComputadora.onRecibiendoDatos, _ AddressOf OtraComputadora_OnRecibiendoDatos End Sub Hoja 18Alejandro Freccero Private Sub OtraComputadora_OnRecibiendoDatos _ (ByVal ComputadoraOrigen As String, ByVal datos As String) MessageBox.Show(String.Format("La computadora '{0}' envio: '{1}'. yo soy la computadora {2}", _ ComputadoraOrigen, datos, Me.Nombre)) End Sub End Class CLASS DIAGRAM EJERCICIO16 FORM1.VB Public Class Form1 Dim listaEmpleados As List(Of Empleado) = New List(Of Empleado) Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim Policial As Tema = New Tema Policial.Descripcion = "Policial" Dim Espectaculos As Tema = New Tema Espectaculos.Descripcion = "Espectaculos" Dim Economia As Tema = New Tema Economia.Descripcion = "Economia" ComboBox1.Items.Add(Policial) ComboBox1.Items.Add(Economia) ComboBox1.Items.Add(Espectaculos) Dim empleado1 As empleadoPermanente = New empleadoPermanente("Alejandro", "Freccero", "0010") Dim empleado2 As empleadoPermanente = New empleadoPermanente("Martin", "Gonzalez", "0023") Dim empleado3 As empleadoPermanente = New empleadoPermanente("Gordito", "Pedorro", "0939") Hoja 19Alejandro Freccero Dim empleado4 As empleadoContratado = New empleadoContratado("Luis", "Capra", "20-30889323-5") Dim empleado5 As empleadoContratado = New empleadoContratado("Alejandro", "Magno", "20-30812343-5") empleado1.SubscribirTema(Economia) empleado2.SubscribirTema(Policial) empleado3.SubscribirTema(Espectaculos) empleado4.SubscribirTema(Policial) empleado5.SubscribirTema(Economia) listaEmpleados.Add(empleado1) listaEmpleados.Add(empleado2) listaEmpleados.Add(empleado3) listaEmpleados.Add(empleado4) listaEmpleados.Add(empleado5) End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim Noticia As Tema = New Tema Noticia = ComboBox1.SelectedItem Noticia.NotificarSubscriptores(TextBox1.Text) End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim a As Empleado = New Empleado Dim TempArr As ArrayList = New ArrayList For Each a In listaEmpleados TempArr = a.ListarNoticias() Dim i As String = String.Empty For Each i In TempArr ListBox1.Items.Add(a.Nombre + " " + a.Apellido + " " + i) Next TempArr.Clear() Next End Sub Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged End Sub End Class TEMA.VB Public Class Tema Public Event OnNotificarSubscriptores As DelegadoNoticia Public Delegate Sub DelegadoNoticia(ByVal Noticia As String) Private _descripcion As String Public Property Descripcion() As String Get Return _descripcion End Get Set(ByVal value As String) _descripcion = value End Set End Property Hoja 20Alejandro Freccero Public Sub NotificarSubscriptores(ByVal Noticia As String) RaiseEvent OnNotificarSubscriptores(Noticia) End Sub Public Overrides Function ToString() As String Return Me.Descripcion End Function End Class EMPLEADOPERMANENTE.VB Public Class empleadoPermanente Inherits Empleado Private _legajo As String Public Property Legajo() As String Get Return _legajo End Get Set(ByVal value As String) _legajo = value End Set End Property Public Sub New(ByVal name As String, ByVal last As String, ByVal leg As String) Legajo = leg Nombre = name Apellido = last End Sub End Class EMPLEADOCONTRATADO.VB Public Class empleadoContratado Inherits Empleado Private _cuil As String Public Property CUIL() As String Get Return _cuil End Get Set(ByVal value As String) _cuil = value End Set End Property Public Sub New(ByVal name As String, ByVal last As String, ByVal cuitt As String) CUIL = cuitt Nombre = name Apellido = last End Sub End Class EMPLEADO.VB Public Class Empleado Dim ListaNoticias As ArrayList = New ArrayList Private _apellido As String Public Property Apellido() As String Get Return _apellido Hoja 21Alejandro Freccero End Get Set(ByVal value As String) _apellido = value End Set End Property Private _nombre As String Public Property Nombre() As String Get Return _nombre End Get Set(ByVal value As String) _nombre = value End Set End Property Sub LlegaNuevaNoticia(ByVal noticia As String) ListaNoticias.Add(noticia) End Sub Sub SubscribirTema(ByVal tema As Tema) AddHandler tema.OnNotificarSubscriptores, AddressOf LlegaNuevaNoticia End Sub Function ListarNoticias() As ArrayList Dim Noticias As ArrayList = New ArrayList Dim o As String = String.Empty For Each o In ListaNoticias Noticias.Add(o) Next Return Noticias End Function End Class Hoja 22Alejandro Freccero CLASS DIAGRAM PRINT SCREEN EJERCICIO17 FORM1.VB Imports System.Text Partial Public Class Form1 Hoja 23Alejandro Freccero Inherits Form Private lista As IList = New ArrayList() Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim profe As New Profesor("Juan", "Perez", "Programacin orientada a Objetos") Dim alum As New Alumno("Roberto", "Gomez", "123456") Dim ayud As New Ayudante("Pedro", "Lopez", "321456", "Lenguajes de Ultima Generacin") lista.Clear() lista.Add(profe) lista.Add(alum) lista.Add(ayud) ListBox1.DataSource = Nothing ListBox1.DataSource = lista End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click For Each persona As Persona In lista Dim sb As New StringBuilder sb.AppendLine("Nombre: " + persona.nombre) sb.AppendLine("Apellido: " + persona.apellido) If TypeOf persona Is Iprofesor Then Dim profesor As Iprofesor = DirectCast(persona, Iprofesor) sb.AppendLine("Materia: " + profesor.materia) End If If TypeOf persona Is Alumno Then Dim alumno As Alumno = DirectCast(persona, Alumno) sb.AppendLine("legajo: " + alumno.legajo) End If Next End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load End Sub End Class ALUMNO.VB Public Class Alumno Inherits Persona Private _legajo As String Public Property Legajo() As String Get Return _legajo End Get Set(ByVal value As String) _legajo = value End Set End Property Public Sub New() End Sub Public Sub New(ByVal _nombre As String, ByVal _apellido As String, ByVal _legajo As String) Hoja 24Alejandro Freccero Me.Nombre = _nombre Me.Apellido = _apellido Me.Legajo = _legajo End Sub End Class PROFESOR.VB Public Class Profesor Inherits Persona Implements Iprofesor Public Property Materia() As String Implements Iprofesor.Materia Get Return _materia End Get Set(ByVal value As String) _materia = value End Set End Property Private _materia As String Public Sub New(ByVal _nombre As String, ByVal _apellido As String, ByVal _materia As String) Me.Nombre = _nombre Me.Apellido = _apellido Me.Materia = _materia End Sub End Class PERSONA.VB Public MustInherit Class Persona Private _nombre As String Public Property Nombre() As String Get Return _nombre End Get Set(ByVal value As String) _nombre = value End Set End Property Private _apellido As String Public Property Apellido() As String Get Return _apellido End Get Set(ByVal value As String) _apellido = value End Set End Property Public Overrides Function ToString() As String Return Nombre + " " + Apellido End Function End Class Hoja 25Alejandro Freccero IPROFESOR.VB Public Interface Iprofesor Property Materia() As String End Interface AYUDANTE.VB Public Class Ayudante Inherits Alumno Implements Iprofesor Public Property Materia() As String Implements Iprofesor.Materia Get Return _materia End Get Set(ByVal value As String) _materia = value End Set End Property Private _materia As String Public Sub New() End Sub Public Sub New(ByVal _nombre As String, ByVal _apellido As String, ByVal _legajo As String, ByVal _materia As String) Me.Nombre = _nombre Me.Apellido = _apellido Me.Legajo = _legajo Me.Materia = _materia End Sub End Class CLASS DIAGRAM Hoja 26Alejandro Freccero PRINT SCREEN EJERCICIO18 FORM1.VB Public Class Form1 Dim lista As ArrayList = New ArrayList Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim persona1 As Persona = New Persona persona1.Nombre = "Alejandro" persona1.Apellido = "Freccero" Dim persona2 As Persona = New Persona persona2.Nombre = "Martin" Dim animal1 As Animal = New Animal animal1.Edad = 21 animal1.Nombre = "Elefante Trompita" Dim animal2 As Animal = New Animal animal2.Nombre = "Tigresa" lista.Add(persona1) lista.Add(persona2) lista.Add(animal1) lista.Add(animal2) End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim o As Object = New Object For Each o In lista MsgBox(o.InfoValidacion()) Next End Sub End Class IVALIDABLE.VB Public Interface IValidable ReadOnly Property InfoValidacin() As String Function EsValido() As Boolean End interface ANIMAL.VB Public Class Animal Hoja 27Alejandro Freccero Implements IValidable Private _edad As Integer Public Property Edad() As Integer Get Return _edad End Get Set(ByVal value As Integer) _edad = value End Set End Property Private _nombre As String Public Property Nombre() As String Get Return _nombre End Get Set(ByVal value As String) _nombre = value End Set End Property Sub New() End Sub Public Overrides Function ToString() As String Return _info End Function Public Function EsValido() As Boolean Implements IValidable.EsValido If Edad = 0 Or Nombre = String.Empty Then _info = "Falta completar alguna propiedad" Return False Else _info = "La clase esta completa" Return True End If End Function Private _info As String Public ReadOnly Property InfoValidacion() As String Implements IValidable.InfoValidacion Get Return _info End Get End Property End Class PERSONA.VB Public Class Persona Implements IValidable Private _nombre As String Public Property Nombre() As String Get Return _nombre End Get Set(ByVal value As String) _nombre = value End Set End Property Hoja 28Alejandro Freccero Private _apellido As String Public Property Apellido() As String Get Return _apellido End Get Set(ByVal value As String) _apellido = value End Set End Property Public Function EsValido() As Boolean Implements IValidable.EsValido If Nombre String.Empty And Apellido String.Empty Then _info = "La validacin fue satisfactoria" Return True Else _info = String.Empty If Nombre = String.Empty Then _info = _info + " El nombre esta en blanco" End If If Apellido = String.Empty Then _info = _info + "El apellido esta en blanco" End If Return False End If End Function Private _info As String Public ReadOnly Property InfoValidacin() As String Implements IValidable.InfoValidacin Get Return _info End Get End Property Public Sub New(ByVal n As String, ByVal a As String) Me.Nombre = n Me.Apellido = a End Sub Public Overrides Function ToString() As String Return String.Format("Nombre: {0}, Apellido: {1}", Nombre, Apellido) End Function End Class CLASS DIAGRAM Hoja 29Alejandro Freccero PRINT SCREEN EJERCICIO19 FORM1.VB Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim list As CustomList = New CustomList list.add("UNO") list.add("DOS") list.add("TRES") For Each o As String In list MessageBox.Show(o) Next End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load End Sub End Class IVALIDABLE.VB Public Interface IValidable ReadOnly Property InfoValidacin() As String Function EsValido() As Boolean End interface CUSTOMLISTENUMERATOR.VB Public Class CustomListEnumerator Implements IEnumerator Private list As IList Private i As Integer = -1 Hoja 30Alejandro Freccero Public ReadOnly Property Current() As Object Implements System.Collections.IEnumerator.Current Get Return list(i) End Get End Property Public Function MoveNext() As Boolean Implements System.Collections.IEnumerator.MoveNext i = i + 1 Return i < list.Count End Function Public Sub Reset() Implements System.Collections.IEnumerator.Reset i = -1 End Sub Public Sub New(ByVal l As IList) list = l End Sub End Class CUSTOMLIST.VB Public Class CustomList Implements IEnumerable Dim list As ArrayList = New ArrayList Public Sub add(ByVal o As Object) list.Add(o) End Sub Public Function GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Return New CustomListEnumerator(list) End Function End Class CLASS DIAGRAM PRINT SCREEN EJERCICIO20 Hoja 31Alejandro Freccero FORM1.VB Public Class Form1 Dim tutu As Auto = New Auto Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load tutu.Puertas = 5 tutu.GPS = True tutu.Codigo = "010202" ListBox1.Items.Add(tutu) End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim a As Auto = New Auto a = tutu.Clone a.Codigo = TextBox1.Text a.GPS = CheckBox1.Checked a.Puertas = TextBox2.Text ListBox1.Items.Add(a) End Sub End Class AUTO.VB Public Class Auto Implements ICloneable Private _codigo As String Public Property Codigo() As String Get Return _codigo End Get Set(ByVal value As String) _codigo = value End Set End Property Private _gps As Boolean Public Property GPS() As Boolean Get Return _gps End Get Set(ByVal value As Boolean) _gps = value End Set End Property Private _puertas As Integer Public Property Puertas() As Integer Get Return _puertas End Get Set(ByVal value As Integer) _puertas = value End Set End Property Function Precio() As Integer Dim valor As Integer = 1000 If Puertas > 4 Then Hoja 32Alejandro Freccero valor = valor + 500 End If If GPS = True Then valor = valor + 500 End If Return valor End Function Public Overrides Function ToString() As String Return "Codigo: " & Codigo & "" & "$" & Me.Precio() End Function Public Function Clone() As Object Implements System.ICloneable.Clone Dim a1 As Auto = New Auto a1.Codigo = _codigo a1.GPS = _gps a1.Puertas = _puertas Return a1 End Function End Class CLASS DIAGRAM Hoja 33Alejandro Freccero PRINT SCREEN EJERCICIO21 FORM1.VB Public Class Form1 Dim listaClientes As List(Of Cliente) = New List(Of Cliente) Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim c1 As Cliente = New Cliente Dim c2 As Cliente = New Cliente Dim c3 As Cliente = New Cliente c1.Apellido = "Gonzalez" c2.Apellido = "Gonzalez" c1.Nombre = "Alejandro" c2.Nombre = "Martin" c3.Apellido = "Alvarez" c3.Nombre = "Jonte" listaClientes.Add(c1) listaClientes.Add(c2) listaClientes.Add(c3) ListBox1.Items.Add(c1) ListBox1.Items.Add(c3) ListBox1.Items.Add(c2) End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click listaClientes.Sort() ListBox1.DataSource = listaClientes End Sub End Class CLIENTE.VB Public Class Cliente Implements IComparable(Of Cliente) Hoja 34Alejandro Freccero Private _apellido As String Public Property Apellido() As String Get Return _apellido End Get Set(ByVal value As String) _apellido = value End Set End Property Private _edad As Integer Public Property Edad() As Integer Get Return _edad End Get Set(ByVal value As Integer) _edad = value End Set End Property Private _nombre As String Public Property Nombre() As String Get Return _nombre End Get Set(ByVal value As String) _nombre = value End Set End Property Sub New() End Sub Public Overrides Function ToString() As String Return Apellido + vbTab + vbTab + Nombre End Function Public Function CompareTo(ByVal other As Cliente) As Integer Implements System.IComparable(Of Cliente).CompareTo If Apellido > other.Apellido Then Return 1 End If If Apellido > other.Apellido Then Return -1 End If If Apellido = other.Apellido Then If Nombre > other.Nombre Then Return 1 End If If Nombre < other.Nombre Then Return -1 End If If Nombre = other.Nombre Then Return 0 End If End If End Function End Class Hoja 35Alejandro Freccero CLASS DIAGRAM PRINT SCREEN