Patricia López
Grupo de Computadores y Tiempo Real
Introducción a JavaBeans
Primer modelo de componentes de Java
Definición:
“A Java Bean is a reusable software component that can be
manipulated visually in a builder tool”
Un JavaBean es una clase puramente Java desarrollada con unos patrones
de diseño bien definidos, que:
Permiten que sea usada en posteriores aplicaciones
Permiten gestionar los componentes de forma automática
Es un modelo sencillo, soportado directamente por el entorno Java =>
Multiplataforma (aunque no multilenguaje)
Ejemplos de JavaBeans: Librerías gráficas AWT (Sun), y SWT (Eclipse)
Santander, 2009
Patricia López
2
1
Modelo de componentes JavaBeans
JavaBeans representa una implementación del módelo Propiedad-Evento-Método
Un componente JavaBean se define a través de :
Las propiedades que expone
Los métodos que ofrece
Los eventos que atiende o genera
Property
Method
Interface
Event Source
Event Sink (listener)
Bounded property
v
Vetoable property
Java class
JavaBeans component
Para gestionar estas características, todo JavaBean debe ofrecer:
Soporte para “Introspection”: El bean tiene que ofrecer la información necesaria para que
la herramienta de diseño pueda analizar sus características de forma opaca.
Soporte para “Customization”: La herramienta de construcción de la aplicación puede
adaptar (“customizar”) la apariencia o comportamiento del bean a la aplicación.
Soporte para Persistencia: El estado de un bean customizado puede ser almacenado para
ser utilizado más tarde.
Soporte para Eventos: Los beans se comunican a través del envío y recepción de eventos.
Santander, 2009
Patricia López
Patrón de diseño básico de un JavaBean
Reglas de diseño básicas para la construcción de un JavaBean:
Clases públicas
Constructor vacío por defecto (puede tener más)
Implementación de la interfaz Serializable (para poder implementar persistencia)
Seguir las convenciones de nombres establecidas (se ven a continuación)
public class MiPrimerBean implements Serializable {
String miProp;
public MiPrimerBean(){
miProp = "";
}
public void myMethod(){
System.out.println("Ejemplo sencillo de JavaBean")
}
public void setMiProp(String s){
miProp = s
}
public String getMiProp (){
return miProp;
}
}
Santander, 2009
Patricia López
3
4
2
Propiedades
Son atributos con nombre que definen el estado y el comportamiento del
componente.
Patrón de diseño:
public void set<PropertyName> (<PropertyType> value);
public <PropertyType> get<PropertyName>();
Si la propiedad es booleana, el metodo de acceso es:
public boolean is<PropertyName>();
Estos métodos constituyen el único modo de acceso a las propiedades.
Tipos de propiedades:
Simples : con un valor único
Indexed: Representa arrays de valores. En este caso los métodos de acceso son los
siguientes:
public void set<PropertyName> (<PropertyType>[] value);
public <PropertyType>[] get<PropertyName>();
public void set<PropertyName> (<PropertyType> value, int index);
public <PropertyType> get<PropertyName>(int index);
Es el único parámetro que reciben los manejadores de eventos.
Encapsulan toda la información asociada a la ocurrencia de un evento. Entre ella el
objeto que lanza el evento.
Todos heredan de la clase java.util.EventObject.
Por cada tipo de evento que exista en la aplicación definiremos una subclase
denominada <NombreEvento>Event.
Ejemplo : Evento que notifica un cambio de temperatura
public class TempChangedEvent extends java.util.EventObject
{
// the new temperature value
protected double theTemperature;
// constructor
public TempChangedEvent(Object source, double temperature)
{
super(source);
// save the new temperature
theTemperature = temperature;
}
// get the temperature value
public double getTemperature()
{
return theTemperature;
}
Santander, 2009
Patricia López
7
EventListeners
Son los objetos que requieren notificación de la ocurrencia de eventos.
La notificación del evento se produce por invocación de métodos manejadores en el
objeto “listener”.
Los métodos manejadores se agrupan en interfaces que extienden a la interfaz
java.util.EventListener.
Por cada tipo de evento que se quiera manejar, se define una interfaz denominada
<NombreEvento>Listener
Los métodos para el manejo de eventos siguen un patrón:
// this method is called whenever the ambient temperature changes
void tempChanged(TempChangedEvent evt);
}
// Ejemplo de objeto “listener” de eventos de tipo TempChangedEvent
class Termomether implements TempChangedListener {
public void tempChanged(TempChangedEvent evt) {
...
}
}
Santander, 2009
Patricia López
8
4
Event Sources
Son los objetos que generan y lanzan eventos
Proporcionan métodos para que los objetos “listener” puedan registrarse en
ellos y así ser notificados de los eventos que se produzcan.
Estos métodos siguen el siguiente patrón de diseño:
public void add<ListenerType>(<ListenerType> listener);
public void remove<ListenerType>(<ListenerType> listener);
Toda clase que presente el anterior patrón se identifica como fuente de
eventos del tipo correspondiente a ListenerType
Cuando se produce un evento es notificado a todas los listeners que se
hayan registrado (Multicast delivery)
Existe también la posibilidad de notificar el evento en modo unicast:
public void add<ListenerType>(<ListenerType> listener) throws
java.util.TooManyListenersException;
public void remove<ListenerType>(<ListenerType> listener);
La invocación de los métodos de notificación en los objetos listener se
realiza de forma síncrona
Santander, 2009
Patricia López
9
Ejemplo de notificación de evento
public class Temperature {
// the new temperature value
protected double currentTemp;
// list of Listeners for temperature changes
private List<TempChangedListener> listeners = new LinkedList<TempChangedListener>();
public Temperature() {
currentTemp = 22.2;
}
public synchronized void addTempChangedListener(TempChangedListener listener) {
listeners.add(listener);
}
public synchronized void removeTempChangedListener(TempChangedListener listener) {
listeners.remove(mcl);
}
// notify listening objects of temperature changes
protected void notifyTempChanged() {
List<TempChangedListener> l;
// create the event object
TempChangedEvent e = new TempChangedEvent(this, currentTemp);
//Make a copy of the listener object list so that it can not be changed while we are
// firing events
synchronized(this) { l = (LinkedList)listeners.clone(); }
for (int i = 0; i < l.size(); i++) { // deliver it!
(l.elementAt(i)).TempChanged(e);
}
Santander, 2009
Patricia López
10
5
Event adapters
Thermometer
temp1:
Temperature
temp2:
Temperature
public class Thermometer implements TempChangedListener {
public tempChanged(TempChangedEvent e) {
if e.getSource = temp1 {
temp1changed();
elsif e.getSource = temp2
temp2changed();
}
}
}
2. Se registra como
EventListener
Event Source
(JavaBean)
Interface EventListener
<<implementa>>
Referencia al destino
1. Creación del adapter
Event Adapter
Event Listener
(JavaBean)
3. Genera evento
EventObject
4. Se ejecuta el manejador
5. Invoca el procedimiento
correspondiente
Santander, 2009
Patricia López
11
Event adapters: Ejemplo
public class Thermometer
// references to the two temperature objects that we are
monitoring
protected Temperature theTemperature1;
protected Temperature theTemperature2;
// the temperature change adapters
protected TemperatureAdapter1 tempAdapter1;
protected TemperatureAdapter2 tempAdapter2;
public void tempChanged(TempChangedEvent evt)
{
temperature2Changed(evt.getTemperature());
}
}
// constructor
Thermometer()
{
// save references to the temperature objects
theTemperature1 = new Temperature();
theTemperature2 = new Temperature();
// create the adapters
tempAdapter1 = new TemperatureAdapter1(temp1);
tempAdapter2 = new TemperatureAdapter2(temp2);
}
// the first adapter class
class TemperatureAdapter1 implements
TempChangedListener
TemperatureAdapter1(Temperature t)
{
t.addTempChangedListener(this);
}
public void tempChanged(TempChangedEvent evt)
{
temperature1Changed(evt.getTemperature());
{
}
}
// the second adapter class
class TemperatureAdapter2 extends TemperatureAdapter
{
TemperatureAdapter2(Temperature t)
{
t.addTempChangedListener(this);
}
Santander, 2009
// handle changes to Temperature object 1
protected void temperature1Changed(double newTemp)
{
}
// handle changes to Temperature object 2
protected void temperature2Changed(double newTemp)
{
}
}
Patricia López
12
6
Propiedades Bound y Constrained
Bound: Cuand
Links de descarga
http://lwp-l.com/pdf1114
Comentarios de: Tecnología de componentes JavaBeans (0)
Comentarios de: Tecnología de componentes JavaBeans (0)
No hay comentarios