CATEGORII DOCUMENTE |
Asp | Autocad | C | Dot net | Excel | Fox pro | Html | Java |
Linux | Mathcad | Photoshop | Php | Sql | Visual studio | Windows | Xml |
DOCUMENTE SIMILARE |
||||||
|
||||||
Chapter 12 described the utility classes for data structures and random number generation. In this chapter, you will learn more about the other utility classes provided in the JDK environment. We'll discuss the class that deals with sets of bits and the class that helps to tokenize a stream of strings, as well as a wrapper class for finding dates, and advanced classes that encapsulate the Observable-Observer design pattern.
The BitSet class represents sets of bits and provides operations on sets of bits, like logical OR, AND, and XOR. The StringTokenizer class is helpful in obtaining tokens from a string using the delimiter. Because Java is platform independent, manipulating the date independent of the system is very important and Java's Date class performs this function. The advanced utility class Observable provides the necessary behavior for objects to be observable by many other observer objects. When used with the Observer classes, this class helps design low-coupled, reusable systems that have a one-to-many dependency on changes that occur in observable classes. The project developed in this chapter displays the time using different clocks such as a digital clock and an analog clock. The clocks get the time from a central time server in a way that any change in time in the time server is observed and updated by every clock.
The BitSet class encapsulates a set of bits. The set can contain many bits and expands as more bits are added. It can be used to perform logical operations like AND, OR, and XOR between any two BitSets. Methods for clearing and setting bits are provided as member methods. You can clone a set of bits, because BitSet implements the Cloneable interface. This class is used to represent a set of boolean data. Using this class saves memory, as each value takes on only one bit for representation.
For example, consider two sets of bits A and B. There are four bits in each set. Let the values of the bits in A be 0, 0, 1, and 1. Let the values of the bits in set B be 0, 1, 0, and 1. Consider the logical AND, OR, and XOR operation over these two sets. In our discussion, a value of 1 indicates that the bit is set, and 0 indicates a clear bit. During an AND operation, the result of ANDing two bits is 1 if both the bits have a value of 1. If either of the bits is 1, the result is 0. In the case of an OR operation, the result value is 0 only if both the bits are of value 0. If one of them has a value of 1, the result is 1. If both the bits have the same value and if you perform XOR operation on them, the result is 0. When you apply an XOR operation on two bits whose values vary, the result is 1. These relationships are expressed in Figure 13-1.
Figure 13-1 Logical AND, OR, and XOR operations performed on
sets of bits
In computer languages, compilers play an important role. User-written code is parsed by the lexical analyzer to separate the individual tokens and verify their validity. In communications, messages are passed between entities and deciphered by the receiving party. In either environment, instead of parsing character by character, it is faster and more logical to parse tokens. A token can be a single word or a set of words. The delimiter specified in each case determines what constitutes a token. Delimiters are by default white space characters. Alternatively, you can specify your own delimiter, providing all the recipients are aware of it. This knowledge of the delimiter is vital in successful communications. Consider the string "Greetings. You are a Java Expert." If you consider white space as the delimiter, parsing the above string will result in six tokens, whereas, if you consider a period ('.') as the delimiter, there are only two tokens as shown in Figure 13-2. You can also specify whether the delimiters should be a part of the token. The StringTokenizer class in Java is useful to obtain tokens from a specified string.
Figure 13-2 Tokens form the same string differ if the
delimiter is different
In many applications you develop, obtaining the time and date or timing a process is important. You have to be aware of the system calls or library routines that provide these details and, most importantly, of how they differ from system to system, depending on the operating system. In Java, you are relieved of this trouble by the Date utility class, a wrapper class for dates. You can obtain the local time as well as the Greenwich Meridian Time (GMT), also known as Universal Time (UT) in technical terms. You can use the Date class to find out what day of the week you were born on, by specifying your date of birth. You can also use the Date class to time your processes and applications which will help you measure their performance. With the support of Java's AWT, you can generate graphs and bar charts too! This chapter covers methods available in the Date class and ways to use them in great detail.
Imagine an application in which you want to define a one-to-many dependency between objects, so that when one of the objects experiences a change in its state, all its dependent objects are notified and updated automatically. This is a common design issue and the pattern it suggests is called Model-View, Observable-Observer, or Publish-Subscribe.
Consider the profits of a business firm. The firm concentrates on four major projects. You want to gather information about the percentage of profit each project contributes to the firm. Also you are interested in tabulating each profit. Instead of tightly coupling various information gathering programs, you can use one object to keep track of the profits. If it finds an observable change in the profit of the company, it notifies all the observer programs, which update their individual views as illustrated in Figure 13-3. Then if any observer needs more information, it can request it from the observable object (which is called the Subject in the Subject-Observer pattern). If the observable notifies the observers of all the changes, it is push-style programming. If the observable notifies the observers of a change and then they query for more details, it is pull-style programming.
Figure 13-3 Observable-Observer objects keep track of a
firm's profits
This pattern is an interesting utility provided by the JDK. Observable is a class in Java, whereas, Observer is an interface. This interface has to be implemented by objects that want to be one of the observers. Details of using the Observable class and Observer interface are presented with examples in this chapter.
Date and Advanced Classes SummariesTable 13-1 summarizes the classes and interface for the BitSet, StringTokenizer, Observable, Observer, and Date utilities.
BitSet Purpose Represents a set of bits and expands automatically as more bits are added to the set. Syntax public class BitSet extends Object implements Cloneable Description BitSet represents a set of bits. The set size increases as more bits are introduced. It is useful to logically operate on a set of bits. This class implements the Cloneable interface and should define the clone() method, so it can be cloned. BitSet supports operations like AND, OR, and XOR of the target set with another set. Figure 13-4 illustrates the inheritance relationship of class BitSet.
PackageName java.util Imports import java.util.BitSet; Constructors public BitSet() Parameters size The initial size of the set of bits to be created. Example The bitsetDemo class in Listing 13-1 illustrates the use of the BitSet class. It has a member of type BitSet and is used to demonstrate the methods of this class. Listing 13-1 bitsetDemo.java: Code demonstrating the usage of Bitset class and its methods import java.util.BitSet;public class bitsetDemo public bitsetDemo(int size) public void debug(String str) public void setStatus(int bitno) public boolean getStatus(int bitno) public BitSet allStatus() public BitSet andWith(BitSet tmp) public BitSet orWith(BitSet tmp) public void clearAll() public final static void main(String args[]) |
and(BitSet)
ClassName
BitSet
Purpose
Logically ANDs the target object with the specified object.
Syntax
public void and(BitSet bs)
Parameters
bs
The specified BitSet object that the target object is ANDed.
Description
This method applies the logical AND operation to the bits in the target object and the bits in the specified object, bs. Each bit in the target object is ANDed with the bits at the corresponding index in the specified bit set. The resultant object is the modified target object.
Imports
import java.utils.BitSet;
Returns
None.
See Also
The or(BitSet) method in theBitSet class
Example
Refer to the method andWith in Listing 13-1. It ANDs two bit sets by using this method.
clear(int)
ClassName
BitSet
Purpose
Clears the specified bit.
Syntax
public void clear(int index)
Parameters
index
The index of the bit in the bit set that has to be cleared, that is set to 0.
Description
The bit at the specified index is cleared by using this method. This way you can selectively clear any individual member in the bit set.
Imports
import java.utils.BitSet;
Returns
None.
See Also
The set method in the BitSet class
Example
Refer to the main method in Listing 13-1. The new_set object has its bit at index 4 cleared using this method.
clone()
ClassName
BitSet
Purpose
This method clones the bit set.
Syntax
public void clone()
Parameters
None.
Description
A clone of the BitSet is created using this method. It doesn't copy the values into the new bit set, but creates a shallow copy. This method overrides the clone method in class Object.
Imports
import java.utils.BitSet;
Returns
The clone of the target BitSet object. Return type is Object, which you may typecast to BitSet.
See Also
The Cloneable interface
Example
Refer to the allStatus method in Listing 13-1. The Bitset is cloned and the newly created clone is returned by the method.
equals(Object)
ClassName
BitSet
Purpose
Returns a boolean value indicating if the target object is equal to the specified bit set object. It returns true if the objects are the same and false if they are not equal.
Syntax
public void equals(Object obj)
Parameters
obj
The object instance to be compared with.
Description
The bit at the specified index is cleared using this method. This way you can selectively clear any individual member in the bit set.
Imports
import java.utils.BitSet;
Returns
None.
Example
Refer to the main method in Listing 13-1. The new_set object has its bit at index 4 cleared using this method.
get(int)
ClassName
BitSet
Purpose
Obtains the specified bit.
Syntax
public boolean get(int index)
Parameters
index
The index of the bit in the bit set that has to be obtained.
Description
The bit at the specified index is retrieved using this method.
Imports
import java.utils.BitSet;
Returns
A boolean value indicating the value of the bit at the specified location.
See Also
The set method in the BitSet class.
Example
Refer to the getStatus method in Listing 13-1. This method is used to obtain the bit at the specified location.
hashCode()
ClassName
BitSet
Purpose
Obtains the hash code of the target bit set object.
Syntax
public int hashCode()
Parameters
None.
Description
The hash code of the target bit set object is returned by this method. It overrides the hashCode method of class Object.
Imports
import java.utils.BitSet;
Returns
The hash code of the target object. Return type is int.
Example
Refer to the clearAll method in Listing 13-1. The hashCode method is used to debug the object information.
or(BitSet)
ClassName
BitSet
Purpose
Logically ORs the target object with the specified object.
Syntax
public void or(BitSet bs)
Parameters
bs
The specified BitSet object that the target object is ORed.
Description
This method applies the logical OR operation to the bits in the target object and the bits in the specified object, bs. Each bit in the target object is ORed with the bits at the corresponding index in the specified bit set. The resultant object is the modified target object.
Imports
import java.utils.BitSet;
Returns
None.
See Also
The and(BitSet) method in the BitSet class
Example
Refer to the orWith method in Listing 13-1. It ORs two bit sets by using this method.
set(int)
ClassName
BitSet
Purpose
Sets the specified bit.
Syntax
public void set(int index)
Parameters
index
The index of the bit that has to be set.
Description
The bit at the specified index is set using this method. The value of the bit will be made 1.
Imports
import java.utils.BitSet;
Returns
None.
See Also
The get method in the BitSet class.
Example
Refer to the setStatus method in Listing 13-1. This method is used to set the value of the bit at the specified location.
size()
ClassName
BitSet
Purpose
Obtains the size of the bit set.
Syntax
public int size()
Parameters
None.
Description
The size of the bit set is obtained by using this method. This value reflects the number of bits in the set.
Imports
import java.utils.BitSet;
Returns
A value indicating the size of the bit set is returned. Return type is int.
Example
Refer to the allStatus method in Listing 13-1 where the number of bits in the set is printed to the screen.
toString()
ClassName
BitSet
Purpose
Obtains the string form of the bit set.
Syntax
public String toString()
Parameters
None.
Description
The string representation of the target BitSet object is returned by this method. This method will return a string containing the index of the bits that are set in the bit set. This is usually used for debugging purposes.
Imports
import java.utils.BitSet;
Returns
A string representing the details of the bit set; return type is String.
Example
Refer to the clearAll method in Listing 13-1. This toString method is used to obtain the string representation of the bit set.
xor(BitSet)
ClassName
BitSet
Purpose
Logically XORs the target object with the specified object.
Syntax
public void xor(BitSet bs)
Parameters
bs
The specified BitSet object that the target object is XORed.
Description
This method applies the logical XOR operation to the bits in the target object and the bits in the specified object, bs. Each bit in the target object is XORed with the bits at the corresponding index in the specified bit set. The resultant object is the modified target object. When two identical objects are XORed, the result is an object with all bits cleared.
Imports
import java.utils.BitSet;
Returns
None.
See Also
The and() and or() methods in the BitSet class
Example
Refer to the clearAll method in Listing 13-1. All the bits in the bit set are cleared by the single use of this method on the same object, bs.
StringTokenizer
Purpose
Encapsulates the linear tokenization of a String.
Syntax
public class StringTokenizer extends Object implements Enumeration
Description
StringTokenizer controls the linear tokenizing of strings. It is helpful for parsing strings and to get tokens out of a string. When messages are exchanged between two objects, instead of sending strings for every piece of information, it is useful to send a single string that contains multiple pieces of information, each separated by a delimiter. You can use an instance of StringTokenizer to tokenize the individual pieces of information from the message String received. This class implements the Enumeration interface and, hence, defines the hasMoreElements and nextElement methods of that interface. Figure 13-5 illustrates the inheritance relationship of the StringTokenizer class.
Figure 13-5 Class diagram of the StringTokenizer class
PackageName
java.util
Imports
import java.util.StringTokenizer;
Constructors
public StringTokenizer(String str)
public StringTokenizer(String str, String delim)
public StringTokenizer(String str, String delim, boolean returnDelimsToo)
Parameters
str
The string to be tokenized.
delim
The delimiter specified for use in tokenizing.
returnDelimsToo
A boolean value indicating whether or not you want the delimiters to be returned as tokens.
Example
The docGenerator class in Listing 13-2 demonstrates the use of the StringTokenizer class and its methods.
Listing 13-2 docGenerator.java: Demonstrating the usage of StringTokenizer and its methods
import java.util.StringTokenizer;countTokens()
ClassName
StringTokenizer
Purpose
Obtains the number of tokens in the string using the specified delimiter.
Syntax
public int countTokens()
Parameters
None.
Description
This method counts the number of tokens in the string that is to be tokenized. The current delimiter is used as the delimiter while counting the tokens. This method returns the number of tokens in the string. The value returned is the number of times the nextToken() method is to be called until the end of the stream is reached.
Imports
import java.utils.StringTokenizer;
Returns
The number of tokens in the string using the current delimiter set. Return type is int.
See Also
The nextToken method in the StringTokenizer class
Example
Refer to the decipherMesg method in Listing 13-2. The number of tokens is found using the countTokens method and it is used to decipher each token.
hasMoreElements()
ClassName
StringTokenizer
Purpose
Returns a boolean value indicating whether or not the enumeration has more elements.
Syntax
public boolean hasMoreElements()
Parameters
None.
Description
This method uses the current delimiter and enumerates the tokens as elements in the string. It returns true if there are more elements in the enumeration of the tokens in the string using the current delimiter. If there are no more elements in the enumeration, this method returns false. This method is defined because the StringTokenizer class implements the Enumeration interface.
Imports
import java.utils.StringTokenizer;
Returns
A value of true or false, depending on whether or not there are more elements in the enumeration of the string. Return type is boolean.
See Also
The hasMoreTokens method in the StringTokenizer class; the Enumeration interface
Example
Refer to the decipherMsg method in Listing 13-2. The tokens of the string containing the authors' names with a delimiter of whitespace " " are enumerated using the hasMoreTokens method. Even if you use the hasMoreElements method instead, the effect is the same.
hasMoreTokens()
ClassName
StringTokenizer
Purpose
Returns a boolean value indicating whether or not there are more tokens in the string using the current delimiter.
Syntax
public boolean hasMoreTokens()
Parameters
None.
Description
This method uses the current delimiter and obtains all the tokens in the string. It returns true if there are more tokens to be tokenized in the string using the current delimiter. If there are no more tokens in the string, this method returns false.
Imports
import java.utils.StringTokenizer;
Returns
A value of true or false depending on whether or not there are more tokens in the string. Return type is boolean.
See Also
The hasMoreElements method in the StringTokenizer class
Example
Refer to the decipherMsg method in Listing 13-2. The tokens of the string containing the authors' names with a delimiter of whitespace " " are obtained one by one using the hasMoreTokens method.
nextElement()
ClassName
StringTokenizer
Purpose
Obtains the next object in the enumeration of the tokens in a string.
Syntax
public Object nextElement()
Parameters
None.
Description
This method uses the current delimiter and enumerates the tokens as elements in the string. After enumerating the tokens and making successive calls to this method, the successive elements are returned. It is defined because the StringTokenizer class implements the Enumeration interface. If there are no elements in the enumeration, it throws a NoSuchElementException. This exception should be caught in a try-catch block. It is advisable to use this method only if the hasMoreElements method returns true.
Imports
import java.utils.StringTokenizer;
Returns
The next element in the enumeration, which is the next token in the string using the current delimiter. Return type is Object, which can be typecast to String.
See Also
The nextToken method in the StringTokenizer class
Example
Refer to the decipherMesg method in Listing 13-2. The book title is obtained by getting the first element in the token set using this method. It would have the same effect if you replace nextElement with the call to the nextToken method.
nextToken()
ClassName
StringTokenizer
Purpose
Obtains the next string token from the enumeration of the tokens in a string.
Syntax
public String nextToken()
Parameters
None.
Description
This method uses the current delimiter and enumerates the tokens as elements in the string. After enumerating the tokens, successive calls to this method returns successive elements. It throws a NoSuchElementException if there are no tokens in the String. This exception should be caught in a try-catch block. It is advisable to use this only if the hasMoreTokens method returns true.
Imports
import java.utils.StringTokenizer;
Returns
The next token in the string using the current delimiter is returned.
Return type is String.
See Also
The nextElement method in the StringTokenizer class
Example
Refer to the decipherMesg method in Listing 13-2. The publisher's name is obtained using this method. It would have the same effect if you replaced nextToken with a call to the nextElement method.
nextToken(String)
ClassName
StringTokenizer
Purpose
Obtains the next string token from the enumeration of the tokens in a string using the specified string as delimiter.
Syntax
public String nextToken(String delim)
Parameters
delim
The delimiter to be used when tokenizing the string.
Description
This method uses the specified delimiter and enumerates the remaining tokens as elements in the string. After enumerating the tokens, successive calls to this method return successive elements in the enumeration. The default delimiter for strings if you don't specify one during construction is " ntr", the whitespace characters. You can switch delimiters using this method to get successive tokens. If this method is used, the specified delimiter will remain as the default delimiter for the rest of the tokenizing session, until it is changed again.
Imports
import java.utils.StringTokenizer;
Returns
The next token in the string using the specified delimiter; return type is String.
See Also
The nextElement and nextString methods in the StringTokenizer class
Example
Refer to the decipherMesg method in Listing 13-2. The authors' names are obtained using this method. The names are separated by white spaces, while the categories (title, publisher name, authors' names) are separated by ":" as delimiter. Switching the delimiter to a single space is done using this method.
Observable
Purpose
The Subject class in a Subject-Observer pattern, which can have many observers.
Syntax
public class Observable extends Object
Description
This class should be subclassed by an object that is observable by other observers. This class forms the Subject class in a Subject-Observer pattern or the "data" in the Model-View paradigm. It defines a one-to-many dependency between objects so that when this Observable object changes the observer objects are notified. Notification is achieved by calling the update method of all the observers of this observable object. This design strategy helps in low coupling between the objects. It has methods to add and delete observers and to notify them. Figure 13-6 illustrates the inheritance relationship of class Observable.
Figure 13-6 Class diagram of the Observable class
PackageName
java.util
Imports
import java.util.Observable;
Constructors
public Observable()
Parameters
None.
Example
The clockTimer class in Listing 13-3 subclasses the Observable class. During clock ticks, it notifies all its observer objects, which are instances of digitalClock in this case.
Listing 13-3 clockTimer.java: Illustrates the usage of Observable class and Observer interface
import java.util.*;addObserver(Observer)
ClassName
Observable
Purpose
Adds the specified observer to the observer list for this observable object.
Syntax
public synchronized void addObserver(Observer obs)
Parameters
obs
The observer object for this observable to be added to the list.
Description
This method adds the specified observer object to the observers list. When a change occurs in the observable object all its observers are notified, so the specified object will be notified of changes in the observable object.
Imports
import java.utils.Observable;
Returns
None.
See Also
The deleteObserver and deleteObservers methods in the Observable class
Example
Refer to Listing 13-3. The digitalClock object on construction adds itself to the observer list using this method on the clockTimer object.
clearChanged()
ClassName
Observable
Purpose
Clears the flag within the observable object indicating no change in observable object.
Syntax
public synchronized void clearChanged()
Parameters
None.
Description
This method clears any change in the target observable object. No observer will be notified before a change occurs and the hasChanged method returns true.
Imports
import java.utils.Observable;
Returns
None.
See Also
The setChanged and hasChanged methods in the Observable class
Example
Refer to Listing 13-3. In the tick()method, in the clockTimer class, before any change is noted in the observable time (any change in seconds), this method is used to clear the flag that indicates a change in the observable object.
countObservers()
ClassName
Observable
Purpose
Obtains the number of observers in the observers list of this observable object.
Syntax
public synchronized int countObservers()
Parameters
None.
Description
This method counts and returns the number of observer objects that are observing this observable object. When a change occurs in the observable object all its observers are notified.
Imports
import java.utils.Observable;
Returns
The count of the number of observer objects in the observer list of the observable object. Return type is int.
Example
Refer to Listing 13-3. You can use this method in the Observable clockTimer class to find out the number of observers.
deleteObserver(Observer)
ClassName
Observable
Purpose
Removes the specified observer from the observer list for this observable object.
Syntax
public synchronized void deleteObserver(Observer obs)
Parameters
obs
The observer object, for this observable object to be deleted from the list.
Description
This method deletes the specified observer object from the observer list. The specified object will not be notified of changes to the observable object.
Imports
import java.utils.Observable;
Returns
None.
See Also
The addObserver and deleteObservers method in the Observable class
Example
Refer to Listing 13-3. You can delete an observer by calling this method. The observers add themselves by calling addObserver and, when desired, they can delete themselves from the list using this method.
deleteObservers()
ClassName
Observable
Purpose
Removes all the observers from the observer list for this observable object.
Syntax
public synchronized void deleteObservers()
Parameters
None.
Description
This method deletes all the observer objects from the observer list. There will not be any observer object to be notified of any change that happens to the observable object.
Imports
import java.utils.Observable;
Returns
None.
Example
Refer to Listing 13-3. The clockTimer object can delete all observers after a couple of ticks, and this will result in no update of time in the observer class.
hasChanged()
ClassName
Observable
Purpose
Returns a boolean value, indicating whether or not there is any change in the observable object.
Syntax
public synchronized boolean hasChanged()
Parameters
None.
Description
This method returns a boolean value indicating whether or not the target observable object has undergone a change. This method is used to decide whether the observers should be notified of any change. This method returns true if there is any change. If there is no change in the observable object, this method returns false.
Imports
import java.utils.Observable;
Returns
Returns true if there is a change in the observable object; false otherwise. Return type is boolean.
See Also
The clearChanged method in the Observable class
Example
Refer to Listing 13-3. In the update method in the digitalClock class, before updating the new values, the observable object is checked to see if there is any change in the object. If there is, then the values of the observers are changed and the display method is called.
notifyObservers()
ClassName
Observable
Purpose
Notifies all the observers of the observable object of a change in the object.
Syntax
public synchronized void notifyObservers()
Parameters
None.
Description
This method notifies all the observers in the list of observers in the target Observable object when a change occurs. It results in a call to the update method of the observer objects in the list.
Imports
import java.utils.Observable;
Returns
None.
See Also
The notifyObservers(Object) method in the Observable class
Example
Refer to the tick method in the clockTimer class in Listing 13-3. After there is a change in the time of the clockTimer objects, all the observers (in this case, digitalClock objects) are notified of the change.
notifyObservers(Object)
ClassName
Observable
Purpose
All the observers of the observable object are notified of the change in the specified object in the target Observable object.
Syntax
public synchronized void notifyObservers(Object arg)
Parameters
arg
The changed object whose change has to be made known to observer objects.
Description
This method notifies all the observers in the list of observers in the target Observable object of the change in the specified Object arg. This method is used to notify the observers when a change occurs, and results in a call to the update method of the observer objects in the list. The changed variable arg is also passed as a reference to the update method of the observer objects. This is helpful in that each object checks this arg parameter for the change the observer is interested in. The observers need not check for all the changes that have occurred in the target observable object.
Imports
import java.utils.Observable;
Returns
None.
See Also
The notifyObservers() method in the Observable class
Example
Refer to the tick method in class clockTimer in Listing 13-3. After a change in the time of the clockTimer objects, all the observers (in this case, digitalClock objects) are notified of changes. But if you replace this method with the notifyObservers(arg) method by passing the date object, then the observer can check the changed date. There can be observers that are not observing the change in time and can safely ignore the notification of change in time.
setChanged()
ClassName
Observable
Purpose
Sets the flag within the observable object indicating a change in the observable.
Syntax
public synchronized void setChanged()
Parameters
None.
Description
This method sets a flag indicating a change in the target observable object. An Observer can be notified of this change by calling the notifyObservers method.
Imports
import java.utils.Observable;
Returns
None.
See Also
The clearChanged and hasChanged methods in the Observable class
Example
Refer to Listing 13-3. In the tick() method, in class clockTimer, after the change in the observable time (any change in seconds) is noted, this method is used to set the flag that indicates a change in the observable object.
Observer
Purpose
An Interface useful for objects to act as observers of an observable object and keep track of any changes to the observable object.
Syntax
public interface Observer extends Object
Description
This interface should be implemented by a class that has to behave as an observer of changes in an observable object. This class forms the Observer class in a Subject-Observer pattern or the "viewer" in the Model-View paradigm. An object can behave as an observer for many observable objects. It lists its interest in observing an observable by adding itself to the observers list of the observable object. Any change in the observable object will be communicated to the class implementing this interface by using the update method in this interface. Any class that implements this interface should define the update class such that when notified by the observable object, the target observer object takes appropriate action on the change that has occurred. This design strategy helps in low coupling between the objects. Figure 13-7 illustrates the inheritance relationship of interface Observer.
Figure 13-7 Class diagram of the Observer interface
PackageName
java.util
Imports
import java.util.Observer;
Example
The DigitalClock class in Listing 13-3 implements this interface Observer. Any change in the observable clockTimer class is communicated to this DigitalClock object, so that the DigitalClock object can take appropriate action by using its update method.
update(Observable, Object)
ClassName
Observer
Purpose
Method called by the observable when it notifies all the observers.
Syntax
public abstract void update(Observable obs, Object arg)
Parameters
obs
The observable that calls this update method.
arg
The object that has changed in the observable object.
Description
This method is called by the observable object on the target Observer object. The target object is an observer in the list of observers in the observable object. The parameter obs, is the observable that notifies of the change. This parameter can be used to distinguish between notification calls from different observables, when the target observer object is in the list of many observable objects. This method is called on the observer object when any of the observable objects change and call the notifyObservers method. This is an abstract method and should be defined in the class that implements the Observer interface.
Imports
import java.utils.Observer;
Returns
None.
See Also
The notifyObservers method in the Observable class
Example
Refer to Listing 13-3. The update method is defined in the DigitalClock class, which implements the Observer interface. In this method the change in time is observed.
Date
Purpose
A wrapper class for date, which is useful to manipulate dates in a system-independent way.
Syntax
public class Date extends Object
Description
This is a wrapper object for a date that contains details of date, month, year, hour, minutes, and seconds. It depends on the local time zone. The standard for time used in computers is the Greenwich Meridian Time (GMT), which is equivalent to the Universal Time (UT). The behavior is not 100 percent accurate as it does not reflect the addition of the 'leap second,' introduced every year. The time depends on the underlying operating system and its accurate maintenance of time. For construction, you can specify a set of values for the Date to be created. The arguments need not necessarily fall within the specified range. The fields are normalized before the Date object is created. For example, the 32nd of March will be interpreted as 1st of April. Figure 13-8 illustrates the inheritance relationship of class Date.
Figure 13-8 Class diagram of the Date class
PackageName
java.util
Imports
import java.util.Date;
Constructors
public Date()
public Date(long arg)
public Date(int year, int month, int date)
public Date(int year, int month, int date, int hours, int
mins)
public Date(int year, int month, int date, int hours, int
mins, int secs)
public Date(String str)
Parameters
arg
Time in milliseconds corresponding to the date to be created.
year
A year after 1900.
month
A month number between 0-11.
date
A day of a month with a value between 1-31.
hours
An hour of the day between 0-23.
mins
The minutes past an hour, with a value between 0-59.
secs
The seconds past the minute, with a value between 0-59.
Example
The dateDemo class in Listing 13-4 demonstrates the usage of methods of the Date class. The member of the class is date of type Date. Methods of this object are invoked by using the methods of the dateDemo class.
Listing 13-4 dateDemo.java: Demonstrates the usage of methods of Date class
import java.util.Date;UTC(int, int, int, int, int, int)
ClassName
Date
Purpose
Method that calculates the Coordinated Universal Time (UTC) from the specified year, month, date, hours, minutes, and seconds values passed as parameters to this method. The parameters are not interpreted in the local time zone, but in UTC. This is a static method and hence can be referenced using the class name.
Syntax
public static long UTC(int year, int month, int date, int hours, int mins, int secs)
Parameters
year
A year after 1900.
month
Month of the year, with values between 0-11.
date
Day of the month, with values between 1-31.
hours
Hour of the day, with values between 0-23.
mins
Minutes past an hour, with values between 0-59.
secs
Seconds past the minute, with values between 0-59.
Description
This method is used to calculate a UTC value from the given parameters. The method interprets the parameters in UTC and not in the local time zone.
Imports
import java.utils.Date;
Returns
Returns the time value; return type is long.
Example
Refer to the demoUTCtimes method in Listing 13-4. This UTC method is used for finding the UTC time.
after(Date)
ClassName
Date
Purpose
Returns a boolean value indicating whether or not the target date comes after the specified date.
Syntax
public boolean after(Date date)
Parameters
date
An instance of the Date class.
Description
A date is considered to come after another date, if it occurs after the other date in chronological order. This method returns true if the date value of the target object comes after the value of the specified date object; otherwise, this method returns false.
Imports
import java.utils.Date;
Returns
A boolean value indicating whether the target object came earlier or later than the specified object.
See Also
The before(date) method in the Date class
Example
Refer to Listing 13-4. In the method named timeTheMethod, this method is used to determine whether a date falls after a specified date.
before(Date)
ClassName
Date
Purpose
Returns a boolean value indicating whether or not the target date comes before the specified date.
Syntax
public boolean before(Date date)
Parameters
date
An instance of the Date object.
Description
A date is considered to come before another date, if it occurs before the other date in chronological order. This method returns true if the date value of the target object comes before the value of the specified date object; otherwise, this method returns false.
Imports
import java.utils.Date;
Returns
A boolean value indicating whether the target object came earlier than the specified object.
See Also
The after method in the Date class
Example
Refer to Listing 13-4. In the method named timeTheMethod, the after method is used to determine whether a date falls after a specified date. You can use the before() method in a similar manner.
equals(Object)
ClassName
Date
Purpose
Returns a boolean value indicating whether or not the target date equals the specified date.
Syntax
public boolean equals(Object date)
Parameters
date
An instance of the Date object.
Description
A Date object is equal to another Date object if they have the same values of date and time. This method returns true if the target date equals the date object; otherwise, this method returns false.
Imports
import java.utils.Date;
Returns
A boolean value indicating whether or not the target object is equal to the specified object.
Example
Refer to Listing 13-4. In the timeTheMethod method execution, the date start and date end are checked for equality.
getDate()
ClassName
Date
Purpose
Returns the day of the month in a Date object.
Syntax
public int getDate()
Parameters
None.
Description
This method returns the day of the month. The returned value lies between 1 and 31.
Imports
import java.utils.Date;
Returns
The day of the month with a value between 1 and 31. Return type is int.
See Also
The setDate method in the Date class
Example
Refer to Listing 13-4. In the today() method getDate is used to find today's date.
getDay()
ClassName
Date
Purpose
Returns the day of the week in a Date object.
Syntax
public int getDay()
Parameters
None.
Description
This method returns the day of the week. The returned value lies between 0-6. Sunday is 0 and Saturday is day 6.
Imports
import java.utils.Date;
Returns
The day of the week with a value between 0 and 6. Return type is int.
See Also
The setDate method in the Date class
Example
Refer to Listing 13-4. This method is used in the today() method to find out what day today is. This is done with assistance from the whatDay method.
getHours()
ClassName
Date
Purpose
Returns the hour of the day in a Date object.
Syntax
public int getHours()
Parameters
None.
Description
This method returns the hour of the day. The returned value lies between 0 and 23. Midnight is 0 hours, noon is 12, and 23 indicates 11pm.
Imports
import java.utils.Date;
Returns
The hour of the day with value between 0 and 23. Return type is int.
See Also
The setHours method in theDate class
Example
Refer to Listing 13-4. The now()method in the demoDate class uses the getHours method to find the hours passed for the current day.
getMinutes()
ClassName
Date
Purpose
Returns the minutes in a Date object.
Syntax
public int getMinutes()
Parameters
None.
Description
This method returns the minutes past an hour. The returned value lies between 0 and 59.
Imports
import java.utils.Date;
Returns
The minutes past an hour with a value between 0 and 59. Return type is int.
See Also
The setMinutes method in the Date class
Example
Refer to Listing 13-4. In the now() method, the getMinutes method is used to find the minutes past the hour.
getMonth()
ClassName
Date
Purpose
Returns the month of the year in a Date object.
Syntax
public int getMonth()
Parameters
None.
Description
This method returns the month of the year. The returned value lies between 0 and 11. January is month 0, February is month 1, December is month 11, and so on.
Imports
import java.utils.Date;
Returns
The month of the year. Return type is int.
See Also
The setMonth method in the Date class
Example
Refer to Listing 13-4. In the today() method, the getMonth method is used to find the month of the year and mapping to strings is accomplished by using the whatDay method.
getSeconds()
ClassName
Date
Purpose
Returns the seconds past a minute in a Date object.
Syntax
public int getSeconds()
Parameters
None.
Description
This method returns the seconds past a minute. The returned value lies between 0 and 59.
Imports
import java.utils.Date;
Returns
The seconds past a minute with a value between 0 and 59. Return type is int.
See Also
The setSeconds method in the Date class
Example
Refer to Listing 13-4. In the now() method, the getSeconds method is used to find the seconds.
getTime()
ClassName
Date
Purpose
Returns the number of milliseconds elapsed since epoch.
Syntax
public long getTime()
Parameters
None.
Description
This method returns the number of milliseconds elapsed since the epoch. This method can be used to find the timings of program execution by finding the start and end of the execution.
Imports
import java.utils.Date;
Returns
The milliseconds elapsed since epoch. Return type is long.
See Also
The setTime method in the Date class
Example
Refer to Listing 13-4. In the timeTheMethod method, the time taken to execute 10,000 null loops is found using this method.
getTimezoneOffset()
ClassName
Date
Purpose
Returns the time zone offset between the local time and the standard time, denoted in minutes.
Syntax
public int getTimezoneOffset()
Parameters
None.
Description
This method returns the difference in time between the local time and the standard Universal Time. The offset is calculated and returned in minutes.
Imports
import java.utils.Date;
Returns
The difference in time zones in units of minutes. Return type is int.
Example
Refer to Listing 13-4. In the now() method, the getTimezoneOffset method is used to find the difference in time, between the local time and the standard time, in units of minutes.
getYear()
ClassName
Date
Purpose
Returns the number of years from 1900 till the current day.
Syntax
public int getYear()
Parameters
None.
Description
This method returns the number of years from 1900 till the current day. For example, if the current year is 1997, then this method will return a value of 97.
Imports
import java.utils.Date;
Returns
The years since 1900. Return type is int.
See Also
The setYear method in the Date class
Example
Refer to Listing 13-4. In the now() method, the getYear method is used to find the number of years from 1900 till the current day.
hashCode()
ClassName
Date
Purpose
Obtains the hash code of the target Date object.
Syntax
public int hashCode()
Parameters
None.
Description
The hash code of the target date object is returned by this method. It overrides the hashCode method of the Object class.
Imports
import java.utils.Date;
Returns
The hash code of the target object. Return type is int.
Example
Refer to the now()method in Listing 13-4. The hashCode method is used to debug the object information.
parse(String)
ClassName
Date
Purpose
Parses the given time in string format and converts it to time value.
Syntax
public static long parse(String date_string)
Parameters
date_string
The date in one of the string formats.
Description
This method parses the date that is specified in String format, using one of the standard date specifying conventions. It returns the number of milliseconds elapsed since epoch. This is a static method and, hence, can be invoked directly by using the class name without creating a date object for this purpose
Imports
import java.utils.Date;
Returns
The milliseconds elapsed since epoch for the specified string representation of date. Return type is long.
See Also
The toString, toGMTString, and toLocalString methods in the Date class
Example
Refer to Listing 13-4. The getTimeFromString method takes the string as input and returns the time. It uses this parse method to accomplish the same.
setDate(int)
ClassName
Date
Purpose
Sets the day of the month in a Date object.
Syntax
public void setDate(int day)
Parameters
day
The day of the month, with values between 1 and 31.
Description
This method sets the day of the month. The value specified lies between 1 and 31.
Imports
import java.utils.Date;
Returns
None.
See Also
The getDate method in the Date class
Example
Refer to Listing 13-4. In the demoUTCtimes method, setDate is used to fix the date of the Date object.
setHours(int)
ClassName
Date
Purpose
Sets the hour of the day in a Date object.
Syntax
public void setHours(int hours)
Parameters
hours
The hour that the date object is to be set to.
Description
This method sets the hour of the day. The specified value lies between 0 and 23. Midnight is 0 hours, noon is 12, and 23 indicates 11pm.
Imports
import java.utils.Date;
Returns
None.
See Also
The getHours method in the Date class
Example
Refer to Listing 13-4. The demoUTCtimes()method, in the demoDate class, uses this setHours method to fix the hours passed on the day.
setMinutes(int)
ClassName
Date
Purpose
Sets the minutes in a Date object.
Syntax
public void setMinutes(int mins)
Parameters
mins
The number of minutes past an hour that is to be set as the minutes in the Date object.
Description
This method sets the minutes past an hour for the target Date object. The value lies between 0 and 59.
Imports
import java.utils.Date;
Returns
None.
See Also
The getMinutes method in the Date class
Example
Refer to Listing 13-4. In the demoUTCtimes() method, the setMinutes method is used to fix the minutes past the hour.
setMonth(int)
ClassName
Date
Purpose
Sets the month of the year in a Date object.
Syntax
public void setMonth(int month)
Parameters
month
Month of the year that is to be set as the month in the target Date object.
Description
This method sets the month of the year in the target Date object. The value lies between 0 and 11. January is month 0, February is month 1, December is month 11, and so on.
Imports
import java.utils.Date;
Returns
None.
See Also
The getMonth method in the Date class
Example
Refer to Listing 13-4. In the demoUTCtimes()method, the setMonth method is used to fix the month of the year of the target Date object.
setSeconds(int)
ClassName
Date
Purpose
Sets the seconds past a minute in a Date object.
Syntax
public void setSeconds(int secs)
Parameters
secs
The number of seconds elapsed since the start of the present minute.
Description
This method sets the seconds past the last minute in the target Date object. The value used lies between 0 and 59.
Imports
import java.utils.Date;
Returns
None.
See Also
The getSeconds method in the Date class
Example
Refer to Listing 13-4. In the demoUTCtimes() method, the setSeconds method is used to fix the number of seconds in the Date object.
setTime(long)
ClassName
Date
Purpose
Sets the number of milliseconds elapsed since epoch.
Syntax
public void setTime(long time)
Parameters
time
The number of milliseconds since epoch.
Description
This method sets the number of milliseconds elapsed since the epoch. This effectively sets the date (year, month, day, hours, minutes, seconds).
Imports
import java.utils.Date;
Returns
None.
See Also
The getTime method in the Date class
Example
Refer to Listing 13-4. In the demoUTCtimes method, this method is used to set the time of the date object whose UTC time is already found by using the UTC method in class Date.
setYear(int)
ClassName
Date
Purpose
Sets the number of years from 1900 till the specified day.
Syntax
public void setYear(int year)
Parameters
year
The number of years from 1900 for the target Date object.
Description
This method fixes the number of years from 1900 to be the year attribute of the target Date object. For example, if you want to set the new date to be in 1946, specify 46 as the parameter to this method. If the year specified is out of bounds (if you specify 1997 instead of 97), then an IllegalArgumentException is thrown.
Imports
import java.utils.Date;
Returns
None.
See Also
The getYear method in the Date class
Example
Refer to Listing 13-4. This setYear method is used in method demoUTCtimes to fix the year.
toGMTString()
ClassName
Date
Purpose
Using the GMT conventions, this method converts the date to a string.
Syntax
public String toGMTString()
Parameters
None.
Description
This method converts the target date object into a string representation using the GMT convention. This GMT convention string is returned by this method.
Imports
import java.utils.Date;
Returns
The GMT convention string representation of the date. Return type is String.
See Also
The toString and toLocaleString methods in the Date class
Example
Refer to the now()method in Listing 13-4. The two conventions of time are printed to the screen using this toGMTString method with another method, toLocaleString.
toLocaleString()
ClassName
Date
Purpose
Using the Locale conventions, this method converts the date to a string.
Syntax
public String toLocaleString()
Parameters
None.
Description
This method converts the target date object into a string representation using the locale convention. This locale convention string is returned by this method.
Imports
import java.utils.Date;
Returns
The locale convention string representation of the date. Return type is String.
See Also
The toString and toGMTString methods in the Date class
Example
Refer to now()method in Listing 13-4. The two conventions of time are printed to screen using this toLocaleString method with another method, toGMTString.
toString()
ClassName
Date
Purpose
Using the standard unix ctime conventions, this method converts the date to a string.
Syntax
public String toString()
Parameters
None.
Description
This method converts the target date object into a string representation, using the standard Unix ctime string format convention. This ctime convention string is then returned by this method.
Imports
import java.utils.Date;
Returns
The Unix ctime convention string representation of the date. Return type is String.
See Also
The toGMTString and toLocaleString method in the Date class
Example
Refer to the main()method in Listing 13-4. The details of the date are printed to the standard output terminal using this method.
Display Timer Application
The project for this chapter is a display timer application. It consists of a central timer, which keeps track of the time, and two clock objects that obtain the time information from the central timer and display it in their own style. You will use the Date object to obtain time information. This application will give you some practice in designing entities that are dependent on another object for information. The main goal of developing this application is to become familiar with the Observable-Observer design pattern, which results in low coupling between objects.
First you develop a clockTimer class that will serve as the central timer. This class must subclass the Observable class, because it will be monitored by other clock classes. This observable object will notify other observer objects of each notable change in time. The minimum unit of time you will work with in this application is seconds. When the seconds value changes, the observer objects (clocks, in this case) will be notified of the change.
You'll develop two types of clock: a digital clock and an analog clock, which differ in the way they display the time obtained from the central timer. These clock classes, DigitalClock and AnalogClock, implement the Observer interface, so they can register themselves as observers of the central timer. Implementing the interface means that these clock classes have to define the update method of the Observer interface, so that it updates the display of time in their own style of display. The AnalogClock will display the time with three hands: the hour hand, the minute hand, and the second hand. DigitalClock will display the hour, minutes, and seconds as numerals.
You will develop these two clocks as separate frames that display the time. When the DigitalClock and AnalogClock are constructed, they will register themselves as observers of the clock timer. Whenever there is a notable change in time, the clockTimer will notify all its observers, and these observer objects will then display the time independently in their own style.
In this implementation, you'll develop Threads for each object, so you will have a Thread that keeps track of the time and notifies the observers of the change in time. The observer Threads will keep displaying the current time.
Apart from these classes, you shall have a wrapper class to make these three objects cooperate with each other in displaying the time. This will be displayTimer class, which will create instances of the clock and timer classes and start all the clocks.
Building the Project
1. The first step is to implement the clockTimer class, which subclasses the Observable class. This is also a Thread that keeps track of the time, so this class implements the Runnable interface. This class will have hours, minutes, and seconds as data members. On construction, it will find the current time and assign the values to its members. It will have accessor methods to return the values of these members, when they are requested by other objects. The following code implements these features.
import java.util.*;2. The clockTimer class implements the Runnable interface and also calls the start() method to execute the next step. This method instantiates a Thread for this class. It can pass itself as the target for creating the Thread, because clockTimer implements the Runnable interface. You must also define the run() method because it is the method in the Runnable interface. The run() method will be called by the Thread that is instantiated in the start() method. Enter the following code in the clockTimer class.
Thread timeThread; // thread member of the class3. In the run() method, for every 1 second (1000 milliseconds of sleep) a call is made to a method name tick(). This method updates the clockTimer on every tick (1 second) of the new time (hours, minutes, and seconds). It notifies all the observers in the list of observers of this observable object by calling the notifyObservers() method of the Observable class. Enter the following code inside the clockTimer class to complete the implementation.
public synchronized void tick()4. The next class you'll implement is the DigitalClock class. It is an Observer class that has a Thread for updating the display. Also, this will form a separate frame to display the time. Hence, the DigitalClock class will subclass the Frame class and implement both Observer and Runnable interfaces. It has members to keep track of the time and to display the time on the frame. It also has an Observable object of type clockTimer as a member. This member object is required to access the time after notification. This implementation uses a pull-style design where the Observable notifies the observers and the observers ask for more information from the Observable. Now enter this code for the class DigitalClock.
class DigitalClock extends Frame implements Observer, Runnable5. The Thread creation and the run method are also implemented for the DigitalClock class. These tasks are done in the start() and run() methods of the class. Enter the following code inside the DigitalClock class definition.
Thread clockThread;6. Now you've implemented the methods for object creation and Thread initiation. The DigitalClock implements the Observer interface, so you need to define the update() method of the interface, which is called when the Observable makes a call to the notifyObservers() method. If a call to update is received, it means that a change that interests the class may have occurred, so the Observable member object is queried for the change. After noting the change, the frame is repainted with its new values. This is done by overriding the paint method in the DigitalClock class. After setting a black background, the object displays the time in green numerals. Enter the following two methods, update and paint, inside the DigitalClock class.
public void update(Observable obs, Object arg)7. The AnalogClock you are going to implement is similar to the DigitalClock, except that the display changes. They differ mainly in the way they repaint the screen. Note that implementing the two clocks separately may not be the best design. Alternatively, you could implement a generic Clock class and subclass the class as DigitalClock and AnalogClock class. But we are ignoring design criteria here to focus on implementation issues. Enter the following code to implement the AnalogClock class.
class AnalogClock extends Frame implements Observer, Runnable8. The update method of the Observer interface has to be defined in the AnalogClock class. It updates the members of this class and makes a call to repaint the frame so it displays the new time in analog style.
public void update(Observable obs, Object arg)9. The purpose of calling to repaint in the update(Observable, Object) method is to repaint the frame. We want to display the time using an hour hand, a minutes hand, and a second hand. The hands change their position depending on the values of the member values. We keep track of the various positions of x and y coordinates for these hands, first drawing the earlier visible hands with the background color and then drawing the hands corresponding to the new values of hours, minutes, and seconds with the red color. The present x and y positions, as well as the previous positions, are maintained as data members of this class. Enter the following code inside the AnalogClock class definition.
int xpos;10. Now that you have implemented the three classes for your application, all that remains is to implement the displayTimer class, which will act as a driver to run the three threads that display the time in digital and analog styles. This will be the public class in the implementation. Because the displayTimer will run as a stand-alone application, implementation of the main method is essential. Enter all the classes you created earlier and the following class in a file named displayTimer.java.
public class displayTimer extends java.applet.AppletWhen the displayTimer.java file is compiled and the class file is executed using the Java interpreter, the resultant frames display the analog and the digital clocks, as shown in Figure 13-9.
Figure 13-9 Digital and analog clocks in action
How It Works
When you start the application using the Java interpreter by typing java displayTimer, two frames appear on the screen. The frame titled Digital displays the current time in digital style, where the hours, minutes, and seconds are separated by colons. In Figure 13-9, the time displayed in the Digital frame is 23:11:16, which is 11 minutes and 16 seconds past 11 pm. The frame titled Analog displays the same time as shown in the digital clock, in analog style using three hands: hours, minutes, and seconds. Both of these clocks are Observer objects observing the time from a central time server object, which acts as an Observable. It's time to end this chapter!
Politica de confidentialitate | Termeni si conditii de utilizare |
Vizualizari: 957
Importanta:
Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved