Component Oriented Programming

Download Report

Transcript Component Oriented Programming

Chapter 3
COP with JavaBeans
Component Oriented Programming
1
Major Topics
• Overview of JavaBeans technology
• Discuss the component infrastructure of
JavaBeans
• Introducing the component model of JavaBeans
• Learning the connection model of JavaBeans
• Discussing the deployment model of JavaBeans
• Discuss the key features and techniques of
component oriented programming with
JavaBeans
Component Oriented Programming
2
JavaBeans
• JavaBeans defines a software component
model for Java, so that third party ISVs
can create and ship Java components that
can be composed together into
applications” [Sun 1997]
• “A JavaBean is a reusable software
component that can be manipulated
visually in a builder tool” [Sun 1997]
Component Oriented Programming
3
8 Steps to Create a JavaBean (1)
1. Use package statement as the first line
of your source code.
2. Implement the Serializable interface for
persistence.
3. Compile your packaged classes using
the -d option.
4. Create a manifest file to describe the
contents of a JAR file.
Component Oriented Programming
4
8 Steps to Create a JavaBean (2)
5. Create the JAR file for your bean using
the jar utility.
6. Check the files were archived correctly.
7. Test your Java bean wrapped in a JAR
file.
8. Add the bean into the BeanBox.
Component Oriented Programming
5
Four Kinds of Properties
• Simple properties
– Simple properties describing a bean’s appearance
and behavior
• Bound properties
– When their values change, provide event notification
to other objects
• Constrained properties
– Value changes can be okayed or vetoed by other
objects
• Indexed properties
– Multiple-value properties
Component Oriented Programming
6
Simple Properties
• Properties are aspects of a Bean's appearance and
behavior that are changeable at design time.
• Properties are private values accessed through getter
and setter methods.
• Property getter and setter method names follow specific
rules, called design patterns. By using these design
pattern-based method names, JavaBeans-enabled
builder tools (and the BeanBox) can
–
–
–
–
–
–
Discover a Bean's properties
Determine the properties' read/write attributes
Determine the properties' types
Locate an appropriate property editor for each property type
Display the properties' (usually in a property sheet)
Alter those properties (at design time)
Component Oriented Programming
7
Adding a Color Property to
SimpleBean
1. Create and initialize a private instance variable.
private Color color = Color.green;
2. Write a public getter method.
public Color getColor(){ return color; }
3. Write a public setter method.
public void setColor(Color newColor){
color = newColor; repaint(); }
4. Override the paint() method inherited from
Canvas.
public void paint(Graphics g) {
g.setColor(color); g.fillRect(20, 5, 20, 30); }
Component Oriented Programming
8
Bound Properties
• Whenever a bound property changes, notification of
the change is sent to interested listeners.
• A bean containing a bound property must maintain a
list of property change listeners and alert them when
the bound property changes.
• The convenience class PropertyChangeSupport
first implements methods that add and remove
PropertyChangeListener objects from a list and
then fires PropertyChangeEvent objects at those
listeners when the bound property changes.
Component Oriented Programming
9
Implementing Bound Property
Support
1. Import the java.beans package. (accessing to the PropertyChangeSupport
class)
2. Instantiate a PropertyChangeSupport object:
private PropertyChangeSupport changes = new PropertyChangeSupport(this);
3. Implement methods to maintain the property change listener list.
public void addPropertyChangeListener( PropertyChangeListener l) {
changes.addPropertyChangeListener(l); }
public void removePropertyChangeListener( PropertyChangeListener l) {
changes.removePropertyChangeListener(l); }
4. Modify a property's setter method to fire a property change event when the
property is changed. OurButton's setLabel method looks like this:
public void setLabel(String newLabel) { String oldLabel = label; label =
newLabel; sizeToFit(); changes.firePropertyChange("label", oldLabel,
newLabel); }
Note that setLabel stores the old label value, because both the old and new
labels must be passed to firePropertyChange.
public void firePropertyChange(String propertyName, Object oldValue, Object
newValue)
Component Oriented Programming
10
Constrained Properties
• A bean property is constrained when any change to
that property can be vetoed.
• Implementation: 3 parts:
– A source bean containing one or more
constrained properties
– Listener objects that implement the
VetoableChangeListener interface. A listener
object accepts or rejects proposed changes to a
constrained property in the source bean
– A PropertyChangeEvent object containing the
property name and its old and new values.
– Example: JellyBean and Voter
Component Oriented Programming
11
Indexed Properties
• Indexed properties represent collections of
values accessed, like an array, by index.
• Methods to access the entire indexed property
array
– public <PropertyType>[] get<PropertyName>();
– public void set<PropertyName>(<PropertyType>[]
value);
• Methods to access individual values
– public <PropertyType> get<PropertyName>(int
index);
– public void set<PropertyName>(int index,
<PropertyType> value);
Component Oriented Programming
12
Discovering Events
• Using introspection
– public void
add<EventListenerType>(<EventListenerType> a)
– public void
remove<EventListenerType>(<EventListenerType> a)
• Using BeanInfo
– Example: ExplicitButtonBeanInfo.java
– Note: this example works in JDK1.3 but not in
JDK1.4!
Component Oriented Programming
13
Viewing Events
• Select a bean (e.g. OurButton) and then
pull down the Edit > Events menu
• Hooking up events in the BeanBox (e.g.
Juggler animation)
• Generating event adapter classes
(\beanbox\tmp\sunw\beanbox\...)
• The EventMonitor demo bean prints out
source bean event reports at run time
Component Oriented Programming
14
Introspector Class
• Introspection – the capability of a builder
tool to discover information about a bean
• Exposing a bean’s features (P, E, M, but in
BDK, you see only P)
• Using the JDK core reflection API and
design patterns
• How could we (designers) explicitly
expose a bean’s feature?
Component Oriented Programming
15
BeanInfo Class
• A separate, associated class that implements
the BeanInfo interface.
• A BeanInfo class can:
– Expose only those features you want to expose.
– Rely on BeanInfo to expose some Bean features
while relying on low-level reflection to expose others.
– Associate an icon with the target bean.
– Specify a customizer class.
– Segregate features into normal and expert categories.
– Provide a more descriptive display name, or
additional information about a bean feature.
Component Oriented Programming
16
Feature Descriptors
• FeatureDescriptor is the base class for the other descriptor
classes. It declares the aspects common to all descriptor
types.
• BeanDescriptor describes the target Bean's class type and
name, and describes the target Bean's customizer class if it
exists.
• PropertyDescriptor describes the target bean's properties.
• IndexedPropertyDescriptor is a subclass of
PropertyDescriptor, and describes the target Bean's
indexed properties.
• EventSetDescriptor describes the events the target Bean
fires.
• MethodDescriptor describes the target Bean's methods.
• ParameterDescriptor describes method parameters.
Component Oriented Programming
17
5 Steps to Creating a BeanInfo
Class
1. Name your BeanInfo class as:
ClassNameBeanInfo
2. Subclass SimpleBeanInfo.
3. Override the appropriate methods to return the
properties, methods, or events that you want
exposed.
4. Optionally associate an icon with the target
bean.
5. Specify the target bean class, and, if the bean
has a customizer, specify it also.
Component Oriented Programming
18
Customization
1. Using a property editor
•
Each bean property has its own property
editor
2. Using customizers
•
•
Customizers are used when property editors
are not practical or applicable.
Property editors are associated with
individual properties, while a customizer
is associated with a bean.
Component Oriented Programming
19
Property Editors
• Explicit association via a BeanInfo object. E.g., Molecule demo
bean: Within the MoleculeBeanInfo class, the Molecule bean's
property editor is set with the following line of code:
pd.setPropertyEditorClass(MoleculeNameEditor.class);
• Explicit registration via
java.Beans.PropertyEditorManager.registerEditor. This method
takes a pair of arguments: The class type, and the editor to be
associated with that type.
• Name search. If a class has no explicitly associated property editor,
then the PropertyEditorManager searchs for that class's property
editor by:
• Appending "Editor" to the fully qualified class name. For example,
for the java.beans.ComplexNumber class, the property editor
manager would search for the java.beans.ComplexNumberEditor
class.
• Appending "Editor" to the class name and searching a class search
path. The default class path for the BeanBox is sun.beans.editors.
Component Oriented Programming
20
Customizers
• Providing complete control over how to configure or edit
a bean
• Extend java.awt.Component or one of its subclasses.
• Implement the java.beans.Customizer interface This
means implementing methods to register
PropertyChangeListener objects, and firing property
change events at those listeners when a change to the
target Bean has occurred.
• Implement a default constructor.
• Associate the customizer with its target class via
BeanInfo.getBeanDescriptor.
• If a Bean that has an associated Customizer is dropped
into the BeanBox, you will notice a "Customize..." item
on the Edit menu.
Component Oriented Programming
21
Persistence
• All beans must persist.
• A bean persists by having its properties, fields,
and state information saved and restored to and
from storage.
• The mechanism that makes persistence possible
is called serialization.
• When a bean instance is serialized, it is
converted into a data stream and written to
storage. Any applet, application, or tool that uses
that bean can then "reconstitute" it by
deserialization.
Component Oriented Programming
22
Serializable Interface
• The Serializable interface provides automatic
serialization by using the Java Object Serialization tools.
• Classes that implement Serializable must have a noargument constructor. This constructor will be called
when an object is "reconstituted" from a .ser file.
• You don't need to implement Serializable in your class if
it is already implemented in a superclass (but you do
need to make sure works correctly and as you expect
with default serialization).
• All fields but static and transient are serialized. Use the
transient modifier to specify fields you do not want
serialized, and to specify classes that are not
serializable.
Component Oriented Programming
23
Overview of Bean Builder
• The Bean Builder is a tool which allows the
visual assembly of an application by instantiating
and setting the properties of components based
on the JavaBeans component architecture.
• The dynamic behavior of the application is
specified by "wiring" relationships that represent
events handlers and method calls between the
objects in an application.
• The state of this application is saved to and
restored from an XML file. An application is
constructed using the Java API without having to
write a line of source code.
Component Oriented Programming
24
Component Oriented Programming
25
Component Oriented Programming
26
<?xml version="1.0" encoding="UTF-8" ?>
<java version="1.3.0"
class="java.beans.XMLDecoder">
<object class="javax.swing.JPanel">
<void method="add">
<object class="javax.swing.JButton">
<void property="label">
<string>Clear</string>
</void>
<void property="model">
<void property="actionCommand">
<string />
</void>
</void>
<void method="addActionListener">
<object class="java.beans.EventHandler"
method="create">
<class>java.awt.event.ActionListener</class>
<object id="JTextArea0"
class="javax.swing.JTextArea">
<void property="border">
<object
class="javax.swing.border.LineBorder">
<object class="java.awt.Color">
<int>0</int>
<int>0</int>
<int>0</int>
<int>255</int>
</object>
<int>1</int>
</object>
</void>
</object>
Component Oriented Programming
<string>setText</string>
<string>source.actionCommand</string>
</object>
</void>
</object>
</void>
<void method="add">
<object idref="JTextArea0" />
</void>
<void property="layout">
<null />
</void>
</object>
</java>
27
Discussion
• The Bean Builder extends the capabilities
of the original BeanBox by demonstrating
new techniques for persistence, layout
editing and dynamic event adapter
generation.
• The Java Bean was designed for the
construction of graphical user interface
(GUI)?
Component Oriented Programming
28
Summary (1)
• JavaBean is a component model for Java
• A bean has four kinds of properties
– Simple, bound, constrained, and indexed
• BDK is a visual design tool provided by
Sun Microsystems
• There are 5 steps to build a JavaBean
• Events can be discovered by introspection
or BeanInfo class
Component Oriented Programming
29
Summary (2)
• Introspection – the capability of a builder tool to discover
information about a bean
• A BeanInfo class can expose only those features you
want to expose
• There are 5 steps to creating a BeanInfo class
• Customization can be done by property editors or
customizers
• Persistence is done by serialization
• Bean Builder provides more capability for component
compositions
• The component architecture of Java beans could be
described using the similar diagrams used in device
beans and CCM
Component Oriented Programming
30