Cześć,
Potrzębuję przerobić phonebook'a zastępując dziedziczenie przez kompozycję, muszę dodać dodać min. 2 własne komunikatory i uniezależnić kod obiektów od sposobu
przechowywania. Może ktoś pomóc?:)
public class EmailContactPerson extends Person {
private String email;
public EmailContactPerson( String s ){
super( s );
email= "unknown";
}
public EmailContactPerson( String s, String e ){
super( s );
email= e;
}
public void setEmail( String e ) {
email= e;
}
public String toString() {
return super.toString() + " email: " + email;
}
}
import java.util.*;
import java.io.*;
public class PBTest {
public static void main( String [] args ) {
PhoneBook pb= new PhoneBook();
if( args.length == 0 )
return;
try {
pb.readFile( args[0] );
pb.sort();
Iterator<Person> i= pb.iterator();
while( i.hasNext() ) {
Person x= i.next();
if( x instanceof PhoneContactPerson )
((PhoneContactPerson)x).setNumber( 222340000 );
else if( x instanceof EmailContactPerson )
((EmailContactPerson)x).setEmail( x.getName() + "@pw.edu.pl" );
}
pb.writeFile( args[1] );
} catch( IOException e ) {
e.printStackTrace();
}
}
}
public class Person implements Comparable<Person> {
private String name;
public Person( String n ){
name= n;
}
public String getName(){
return name;
}
public String toString() {
return name;
}
public boolean equals( Object o ) {
return o instanceof Person && ((Person)o).name.equals( name );
}
public int hashCode( ) {
return name.hashCode();
}
public int compareTo( Person o ) {
return name.compareTo( o.name );
}
}
import java.util.*;
import java.io.*;
public class PhoneBook {
private ArrayList<Person> contacts;
public PhoneBook(){
contacts= new ArrayList<Person>();
}
public void addContact(Person p){
contacts.add( p );
}
public Person findContact(String n){
for( Person p: contacts )
if( p.getName().equals( n ) )
return p;
return null;
}
public void sort() {
Collections.sort( contacts );
}
public Iterator<Person> iterator() {
return contacts.iterator();
}
public String toString(){
return contacts.toString();
}
public void readFile( String fname ) throws IOException {
BufferedReader r= new BufferedReader( new FileReader( new File( fname ) ) );
String s;
contacts.clear();
while( (s= r.readLine()) != null )
contacts.add( new Person( s ) );
r.close();
}
public void writeFile( String fname ) throws IOException {
FileWriter w= new FileWriter( new File( fname ) );
w.write( this.toString() );
w.close();
}
}
public class PhoneContactPerson extends Person {
private int number;
public PhoneContactPerson( String s ){
super( s );
number= 0;
}
public PhoneContactPerson( String s, int n ){
super( s );
number= n;
}
public void setNumber( int nn ) {
number= nn;
}
public String toString() {
return super.toString() + " tel: " + number;
}
}