Programación en Capas Java
Programación en Capas Java
Hoy haremos un tema que es bastante interesante y muy usado en el desarrollo de software.
Realizaremos un ejemplo de la programacin orientada a capas.
La programacin orientada a capas es una tcnica que se usa para el desarrollo de software
el cual permita que dicho software sea escalable, mantenible, consistente y que tenga una
aspecto mucho ms profesional de desarrollo, no como la clsica programacin secuencial.
La programacin orientada a capas se caracteriza por ser un tipo de diseo en el desarrollo
de software mediante clases las cuales se separan generalmente en:
-La capa de datos.
-La capa de negocios.
-La capa de presentacin.
Bien, como se sabe que lo que Ud. quiere es la parte tcnica ms no la parte terica,
pasaremos a realizar el ejemplo de la programacin orientada a capas.
Tener en cuenta que la programacin en capas generalmente va de la mano con la
programacin orientada a objetos para la optimizacin de este.
Tambin recordar que en la capa de datos se puede crear una clase exclusivamente para las
consultas relacionales ya que la programacin orientada a objetos que va de la mano con la
programacin en capas no permite encapsular este tipo de consultas.
Como en nuestro caso no tenemos una base de datos, simularemos dicho caso con un
formulario que tenga los campos para registrar una persona que lo pasar a un JTable y
luego tendremos un botn que permita leer tales datos almacenados en nuestro JTable.
La estructura de nuestro rbol con las clases creadas debera quedar de la siguiente manera.
Cdigo Fuente
La Clase TPersona
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ENCAPSULAMIENTO;
/**
*
* @author kaaf
*/
public class TPersona {
private String nombre;
private String apellidoPaterno;
private String apellidoMaterno;
private String dNI;
private String direccion;
private int edad;
private char sexo;
public void SetNombre(String nombre)
{
this.nombre=nombre;
}
public String GetNombre()
{
return this.nombre;
}
public void SetApellidoPaterno(String apellidoPaterno)
{
this.apellidoPaterno=apellidoPaterno;
}
public String GetApellidoPaterno()
{
return this.apellidoPaterno;
}
{
return this.sexo;
}
}
La Clase DbTPersona
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package CAPADEDATOS;
import ENCAPSULAMIENTO.TPersona;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
/**
*
* @author kaaf
*/
public class DbTPersona {
public static DefaultTableModel Registrar(TPersona tPersona, JTable miTabla)
{
DefaultTableModel modeloDeDatosTabla=(DefaultTableModel)miTabla.getModel();
Object[] datosRegistro=
{
tPersona.GetNombre(),
tPersona.GetApellidoPaterno(),
tPersona.GetApellidoMaterno(),
tPersona.GetDNI(),
tPersona.GetDireccion(),
tPersona.GetEdad(),
tPersona.GetSexo()
};
modeloDeDatosTabla.addRow(datosRegistro);
return modeloDeDatosTabla;
}
La Clase NegocioFrmPersona
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package CAPADENEGOCIO;
import CAPADEDATOS.DbTPersona;
import ENCAPSULAMIENTO.TPersona;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTable;
/**
*
* @author kaaf
*/
public class NegocioFrmPersona {
public void Registrar(TPersona tPersona, JTable miTabla)
{
try
{
miTabla.setModel(DbTPersona.Registrar(tPersona, miTabla));
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
public List<TPersona> LeerDatosPersona(JTable tablaDeDatos)
{
List<TPersona> listaTPersona=new ArrayList<>();
try
{
listaTPersona=DbTPersona.LeerTodo(tablaDeDatos);
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage());
}
finally
{
return listaTPersona;
}
}
}
Compilando la Aplicacin
Una vez se realiz todos estos pasos la aplicacin debera correr de la siguiente manera.
Tener en cuenta que los datos no fueron validados por lo que debera ingresarse datos
correctos sin dejar ningn dato vaco.
Por otro lado, hay cosas que no debera estar; como pasar el JTable desde la capa de
presentacin hasta la capa de datos. Pero se hace esto porque no se est trabajando con una
base de datos real y se est tomando como base de datos nuestra primera tabla donde
estamos ingresando los datos de la persona.
En un prximo post ya estaremos viendo programacin orientada a objetos con el uso de
una base de datos real, herencia, polimorfismo entre otros.
1.
2.
3.
4.
5.
6.
7.
1. package CapaRecursos;
2.
3.
4. public class Vehiculos {
5.
6. private String marca;
7. private String modelo;
8. private String color;
9.
10.
11.
public void SetMarca(String marca)
12. {
13.
this.marca=marca;
14. }
15.
16. public String GetMarca()
17. {
18.
return this.marca;
19. }
20.
21.
{
22.
this.marca=marca;
23. }
24.
25.
26.
public void SetModelo(String modelo)
27. {
28.
this.modelo=modelo;
29. }
30.
31. public String GetModelo()
32. {
33.
return this.modelo;
34. }
35.
36.
public void SetColor(String color)
37. {
38.
this.color=color;
39. }
40.
41. public String GetColor()
42. {
43.
return this.color;
44. }
45.
46. }
47.
48. }
El cdigo es el siguiente:
1. package CapaAplicacion;
2. import CapaRecursos.Vehiculos
3. /**
4. *
5. * @author alumno
6. */
7. public class frmAutos extends javax.swing.JFrame {
8.
9. /**
10.
* Creates new form frmAutos
11.
*/
12. public frmAutos() {
13.
initComponents();
14. }
15.
16. /**
17.
* This method is called from within the constructor to
initialize the form.
18.
* WARNING: Do NOT modify this code. The content of this
method is always
19.
* regenerated by the Form Editor.
20.
*/
21. @SuppressWarnings("unchecked")
22. // <editor-fold defaultstate="collapsed" desc="Generated Code">
23. private void initComponents() {
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
jLabel1.setText("Marca");
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable1);
txtMarca.setName("marca"); // NOI18N
txtModelo.setToolTipText("");
txtModelo.setName("modelo"); // NOI18N
txtModelo.addActionListener(new
java.awt.event.ActionListener() {
58.
public void
actionPerformed(java.awt.event.ActionEvent evt) {
59.
txtModeloActionPerformed(evt);
60.
}
61.
});
62.
63.
jLabel2.setText("Modelo");
64.
65.
jLabel3.setText("Color");
66.
67.
txtColor.setToolTipText("");
68.
69.
btRegistrar.setText("Registrar");
70.
btRegistrar.setActionCommand("btRegistrar");
71.
btRegistrar.setName("btRegistrar"); // NOI18N
72.
btRegistrar.addActionListener(new
java.awt.event.ActionListener() {
73.
public void
actionPerformed(java.awt.event.ActionEvent evt) {
74.
btRegistrarActionPerformed(evt);
75.
}
76.
77.
78.
79.
80.
81.
82.
});
btLeer.setText("Leer");
btLeer.setToolTipText("");
btLeer.setName("btLeer"); // NOI18N
104.
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
105.
);
106.
layout.setVerticalGroup(
107.
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADIN
G)
108.
.addGroup(layout.createSequentialGroup()
109.
.addContainerGap()
110.
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignm
ent.LEADING)
111.
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignm
ent.BASELINE)
112.
.addComponent(jLabel1)
113.
.addComponent(txtMarca,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
114.
.addComponent(btRegistrar))
115.
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignm
ent.LEADING)
116.
.addGroup(layout.createSequentialGroup()
117.
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED
)
118.
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignm
ent.BASELINE)
119.
.addComponent(jLabel2)
120.
.addComponent(txtModelo, javax.swing.GroupLayout.PREFERRED_SIZE,
15, javax.swing.GroupLayout.PREFERRED_SIZE))
121.
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELAT
ED)
122.
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignm
ent.BASELINE)
123.
.addComponent(jLabel3)
124.
.addComponent(txtColor, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)))
125.
.addGroup(layout.createSequentialGroup()
126.
.addGap(15, 15, 15)
127.
.addComponent(btLeer)))
128.
.addGap(26, 26, 26)
129.
.addComponent(jScrollPane1,
javax.swing.GroupLayout.PREFERRED_SIZE, 181,
javax.swing.GroupLayout.PREFERRED_SIZE)
130.
.addContainerGap(32, Short.MAX_VALUE))
131.
);
132.
133.
pack();
134. }// </editor-fold>
135.
136. private void txtModeloActionPerformed(java.awt.event.ActionEvent
evt) {
137.
// TODO add your handling code here:
138. }
139.
140. private void btRegistrarActionPerformed(java.awt.event.ActionEvent
evt) {
141.
142.
143. }
144.
145. /**
146.
* @param args the command line arguments
147.
*/
148. public static void main(String args[]) {
149.
/* Set the Nimbus look and feel */
150.
//<editor-fold defaultstate="collapsed" desc=" Look and
feel setting code (optional) ">
151.
/* If Nimbus (introduced in Java SE 6) is not available,
stay with the default look and feel.
152.
* For details see
http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf
.html
153.
*/
154.
try {
155.
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
156.
if ("Nimbus".equals(info.getName())) {
157.
javax.swing.UIManager.setLookAndFeel(info.getClassName());
158.
break;
159.
}
160.
}
161.
} catch (ClassNotFoundException ex) {
162.
java.util.logging.Logger.getLogger(frmAutos.class.getName()).log(ja
va.util.logging.Level.SEVERE, null, ex);
163.
} catch (InstantiationException ex) {
164.
java.util.logging.Logger.getLogger(frmAutos.class.getName()).log(ja
va.util.logging.Level.SEVERE, null, ex);
165.
} catch (IllegalAccessException ex) {
166.
java.util.logging.Logger.getLogger(frmAutos.class.getName()).log(ja
va.util.logging.Level.SEVERE, null, ex);
167.
} catch (javax.swing.UnsupportedLookAndFeelException ex)
{
168.
java.util.logging.Logger.getLogger(frmAutos.class.getName()).log(ja
va.util.logging.Level.SEVERE, null, ex);
169.
}
170.
//</editor-fold>
171.
172.
/* Create and display the form */
173.
java.awt.EventQueue.invokeLater(new Runnable() {
174.
public void run() {
175.
new frmAutos().setVisible(true);
176.
}
177.
});
178. }
179.
180. // Variables declaration - do not modify
181. private javax.swing.JButton btLeer;
182. private javax.swing.JButton btRegistrar;
183. private javax.swing.JLabel jLabel1;
184. private javax.swing.JLabel jLabel2;
185. private javax.swing.JLabel jLabel3;
186. private javax.swing.JScrollPane jScrollPane1;
187. private javax.swing.JTable jTable1;
188. private javax.swing.JTextField txtColor;
189. private javax.swing.JTextField txtMarca;
190. private javax.swing.JTextField txtModelo;
191. // End of variables declaration
192. }
1. mport CapaRecursos.Vehiculos;
1. package CapaDatos;
2.
3. import CapaRecursos.Vehiculos;
4. import java.util.ArrayList;
5. import java.util.List;
6. import javax.swing.JTable;
7. import javax.swing.table.DefaultTableModel;
8.
9. /**
10. *
11. * @author alumno
12. */
13. public class DBAutos {
14.
15. public static DefaultTableModel Registrar(Vehiculos vehiculo,
JTable Jtable1) {
16.
DefaultTableModel modeloDeDatosTabla =
(DefaultTableModel) Jtable1.getModel();
17.
18.
Object[] datosRegistro
19.
= {
20.
vehiculo.GetMarca(),
21.
vehiculo.GetModelo(),
22.
vehiculo.GetColor()
23. };
24.
25. modeloDeDatosTabla.addRow(datosRegistro);
26.
27.
return modeloDeDatosTabla;
28. }
29.
30.
31. public static List<Vehiculos> LeerTodo(JTable lsVehiculos)
32. {
33.
List<Vehiculos> listaVehiculo=new ArrayList<>();
34.
for(int i=0;i<lsVehiculos.getRowCount();i++)
35.
{
36.
Vehiculos vehiculo=new Vehiculos();
37.
vehiculo.SetMarca(lsVehiculos.getValueAt(i,
0).toString());
38.
vehiculo.SetModelo(lsVehiculos.getValueAt(i,
1).toString());
39.
vehiculo.SetColor(lsVehiculos.getValueAt(i,
2).toString());
40.
41.
listaVehiculo.add(vehiculo);
42.
}
43.
44.
return listaVehiculo;
45. }
46. }
47.
1. package CapaNegocio;
2.
3. import CapaDatos.DBAutos;
4. import CapaRecursos.Vehiculos;
5. import java.util.ArrayList;
6. import java.util.List;
7. import javax.swing.JOptionPane;
8. import javax.swing.JTable;
9. /**
10. *
11. * @author alumno
12. */
13. public class negocioautos {
14.
15. public void Registrar(Vehiculos vehiculo, JTable Jtable1)
16. {
17.
try
18.
{
19.
Jtable1.setModel(DBAutos.Registrar(vehiculo,
Jtable1));
20.
}
21.
catch(Exception ex)
22.
{
23.
24.
}
25.
26. }
27.
28. public List<Vehiculos> Leer(JTable tabla)
29. {
30.
List<Vehiculos> listaAutos=new ArrayList<>();
31.
32.
try
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44. }
45.
46. }
{
listaAutos=DBAutos.LeerTodo(tabla);
}
catch(Exception ex)
{
}
finally
{
return listaAutos;
}
1.
2.
3.
4.
5.
6.
import
import
import
import
import
import
CapaRecursos.Vehiculos;
CapaNegocio.negocioautos;
java.util.ArrayList;
java.util.List;
javax.swing.JTable;
javax.swing.table.DefaultTableModel;
mediante el botn leer. Para ello aadimos una Jtable debajo y los
dejamos sin configurar sus propiedades ya que la modificaremos
desde cdigo. Si queremos inspeccionar como modificar los
parmetros por defecto de una tabla, podemos verlos haciendo clic
derecho sobre la tabla y luego en el menu vamos a la opcion
propiedades alli podremos modificar distintas opciones como los
titulos de las columnas, aadir o quitar columnas o filas,
implementar distintos comportamientos al iniciar la aplicacin.
1. private void btLeerActionPerformed(java.awt.event.ActionEvent evt)
{
2.
// TODO add your handling code here:
3.
4.
5. List<Vehiculos> listaVehiculo=new negocioautos().Leer(jTable1);
6.
7.
DefaultTableModel Tabla=new DefaultTableModel();
8.
Tabla.addColumn("Marca");
9.
Tabla.addColumn("Modelo");
10.
Tabla.addColumn("color");
11.
12.
13.
for(Vehiculos vehiculo:listaVehiculo)
14.
{
15.
Object[] registroLeido=
16.
{
17.
vehiculo.GetMarca(),
18.
vehiculo.GetModelo(),
19.
vehiculo.GetColor()
20.
};
21.
22.
Tabla.addRow(registroLeido);
23.
}
24.
25.
jTable2.setModel(Tabla);
26.
27. }
Ventajas y Desventajas
La programacin en capas es una metodologia que permite trabajar
con total libertad, no es una tcnica rgida que debe
Java
La capa de presentacin se implementa por median te las
herramientas JSP, Servlets, tambien en desarrollo de escritorio
con las que se construyen y conectan las interfaces grficas con
la capa de lgica del negocio.
La capa de datos se implementa mediante herramientas como Data Set
y Data Reader. Muy similar a C# en .net
La otra herramienta muy utilizada en Java es Hibernate, que se
utiliza para mapear bases de datos con objetos creados en Java
algo como lo que vimos en el ejemplo con la clase vehiculos salvo
que el mapeo lo hicimos construyendo la clase en forma manual.