1. Trang chủ
  2. » Giáo án - Bài giảng

#11_Abstraction with Interfaces_31_v2.ppt

64 262 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Abstraction with Interfaces
Tác giả Mai Anh Tho
Trường học Hanoi University of Science and Technology
Chuyên ngành Basic Java Programming
Thể loại lecture notes
Thành phố Hanoi
Định dạng
Số trang 64
Dung lượng 428 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Course material developed by Mai Anh Tho tho@hcmuaf.edu.vnALoObject public abstract class ALoObject { }... Course material developed by Mai Anh Tho tho@hcmuaf.edu.vnConsLoObject public c

Trang 1

Part VI Abstraction with Interfaces

Trang 2

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

Comments

Many of the class hierarchies we have

seen look alike

A list of books is similar to a list of

routes or a list of stations

Many methods for these classes look

alike as well - and in some cases are

completely identical

So, for example the code for counting

the number of items in a list looks the

same for all kinds of lists The methods

to determine whether a list contains

some item is similar for all lists

Trang 3

Repeating the same code is a major source

of errors in programs

Modifications and corrections in one

instance may not be reproduced faithfully in

other instances of the same or similar code

By observing the similarities and designing

abstractions that represent the common

behavior we provide a single point of

control

Additionally, the more general code may be

reused in the future in solving similar

Trang 4

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

Abstracting Over Data Definitions

With Object

Trang 5

Usually, we have seen that data with similar properties.

Example :

A List of Authors is one of:

- a empty - a structure of - an Author - a List of Authors

An Author contains - name

Trang 6

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

Q: Why don’t we organize these data into unions of

classes that extend the same base class?

Abstracting over Data Definitions with Object help

us solve this problem.

Trang 7

Compare the definitions and identify the

differences We can see:

The only difference between the data definitions

for the lists is the type of the object that the list

contains

Because every class in Java extends the class

Object we could define instead a list of Objects

Trang 8

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

ALoObject

public abstract class ALoObject { }

Trang 9

public class EmptyLoObject {

public EmptyLoObject() { }

}

Trang 10

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

ConsLoObject

public class ConsLoObject {

private Object first;

private ALoObject rest;

public ConsLoObject( Object first, ALoObject

Trang 11

We now must validate that every list from our

original examples can be represented as a list of

Objects

Trang 12

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

List of Books

Book b1 = new Book("Call of the Wild", 10);

Book b2 = new Book("The Sea-Wolf", 12);

Book b3 = new Book("HtDP", 55);

ALoObject blist =

new ConsLoObject(b2,

new ConsLoObject(b3,

new EmptyLoObject()));

Trang 14

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

Looking at the definitions of earlier

methods that counted the number of

objects in the list

Comparing the two contains methods from

the problem with stations and routes it is

clear that the same code is used to

determine whether a list of Routes contains

a given Route as the code to determine

whether a list of Stations contains a given

Station The only difference is in the

method header: in one case the method

parameter is an instance of Route, in the

other case it is an instance of Station

Trang 15

public abstract class ALoObject {

// count the number of items in this list

public abstract int count();

// determine whether this list contains the given

Trang 16

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

Trang 17

public class ConsLoObject extends ALoObject {

private Object first;

private ALoObject rest;

public boolean contains(Object obj) {

return (this.first.equals(obj)) || this.rest.contains(obj);

}

Trang 18

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

We can use these methods to determine whether a

given instance of Book is in this list, or whether a

given instance of Author is in this list.

Trang 19

Exercises

Trang 20

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

Exercise 1.0.1.   Design a test suite that will define

several lists of Objects that contain only Book

objects and use them to test the methods count and

contains.

– Do the same for lists of Shape objects

Exercise 1.0.2.   Develop the method remove that

removes a given object from a list of objects Test

your method on the classes of Books, and classes of

Shapes.

Trang 21

Abstracting over Data Definitions

with Interfaces

(Part 1)

Trang 22

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

Entry Date d

double distance int duration

ALog rest

+ double

totalDistance()

Trang 23

ALoBooks rest

Book String title Author author

int year int price

Trang 24

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

public class Entry {

// in the abstract class ALog

// compute the total distance

runner

// recorded in this log

public abstract double

totalDistance();

// in the class EmptyLog

public double totalDistance() {

return 0.0;

}      

// in the class ConsLog

public double totalDistance() {

books // in this list public abstract double totalPrice();

// in the class EmptyLoBooks public double totalPrice() { return 0.0;

}      

// in the class ConsLoBooks public double totalPrice() { return ( this.first.getPrice()) +

this.rest.totalPrice());

}

Trang 25

Các phương thức trong hai trường hợp thì giống

nhau, chúng đều tính tổng của các giá trị

Giá trị trong Entry là distance, trong Book là price

Thay vì chỉ định từng giá trị cho mỗi đối tượng cụ thể

thì ta có thể yêu cầu các đối tượng liên quan cung

cấp giá trị của nó thì việc tính toán sẽ trở nên dễ

dàng hơn

Việc trùng lặp dữ liệu là nguyên nhân chủ yếu dẫn

đến những lỗi trong lập trình, một chương trình tốt

thì phải tránh được điều đó

Trang 26

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

//In the class Entry the

method is

public double getValue(){

return this.distance;

}

// in the abstract class Alog

public abstract double

totalValue();

// in the class EmptyLog

public double totalValue() {

return 0.0;

}

// in the class ConsLog

public double totalValue() {

// in the class EmptyLoBooks

public double totalValue() { return 0.0;

}

// in the class ConsLoBooks

public double totalValue() { return

(this.first.getValue()) + this.rest.totalValue();

}

Trang 27

Can we replace the list of Books and the list

of Entries with a list of Objects?

// in the abstract class ALoObject

public abstract double totalValue();

// in the class EmptyLoOjbect

public double totalValue() {

return 0.0;

}

// in the class ConsLoObjects

public double totalValue() {

return (this.first.getValue()) +

Trang 28

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

OK, but…

– The program code in the class ConsLoObject

references this.first.getValue() But the class

Object does not define the method double

getValue()

How to solve this problem?

Trang 29

Định nghĩa ra một interface chịu trách nhiệm cài

đặt phương thức getValue() Các đối tượng Entry

và Book sẽ implements interface này và chịu trách

nhiệm hiện thực phương thức getValue().

public interface IValuable {

public abstract double getValue();

}

Trang 30

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

public class Entry implements IValuable {

public double getValue() {

return this.distance;

}

}

public class Book implements IValuable {

public double getValue() {

return this.price;

}

}

Trang 31

// in the abstract class AList

public abstract double totalValue();

// in the class Empty

public double totalValue() {

return 0.0;

}

// in the class Cons

public double totalValue() {

return ((IValuable)this.first).getValue() +

this.rest.totalValue();

Trang 32

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

double totalValue() <<interface>>

Trang 33

Exercises

Trang 34

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

Exercise 2.0.3.   Design the tests for the

method totalValue that will consume a list

of Books

– Design a similar test for a list of Shape objects.

Exercise 2.0.4.   Develop the method

onlyTheBest that creates a new list of

objects, selecting only those that have a

value greater than some threshold

specified by the user. 

Exercise 2.0.5.   Develop the method

hasValue that determines whether there is

an item in this list that has a value lower

than some value specified by the user. 

Exercise 2.0.6.   Develop the method

allFine that determines whether all objects

in this list have a value greater than some

threshold specified by the user. 

Trang 35

ABSTRACTING OVER DATA

DEFINITIONS WITH INTERFACES

(Part 2)

Trang 36

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

Remind the Sorting examples

Now we compare the method sortByPublicationYear()

in the ALoBooks class and the method

sortByDistance() in the ALog class.

Trang 37

public class ConsLoBook extends ALoBooks {

private Book first;

private ALoBooks rest;

public ALoBooks sortByPublicationYear() {

return this rest.sortByPublicationYear().

insertInPublicationYearOrder( this first);

}

protected ALoBooks insertInPublicationYearOrder(Book b)

{

if (b isOlderThan ( this first))

return new ConsLoBook(b, this );

else

return new ConsLoBook( this first,

this rest.insertInPublciationYearOrder(b));

Trang 38

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

public class ConsLog extends ALog {

private Entry first;

private ALog rest;

protected ALog insertInDistanceOrder(Entry e) {

if (e hasDistanceShorterThan ( this first))

return new ConsLog(e, this );

Trang 39

If we rename the classes to represent a list of

Objects and change the method names of two

examples to sort and insert the two solutions

become nearly identical The only lines where the

differences are not merely cosmetic are

if (b.year < this.first.year)

if (entry.distance < this.first.distance)

Trang 40

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

In general, here we want to compare

some information recorded in the this.first object with similar information recorded

in the object that is the argument to this

function Java libraries include the

interface Comparable defined as follows:

interface Comparable{

// compare this object with the given object

// produce negative result if this is 'smaller' than the given

object

// produce zero if this object is 'the same' as the given object

// produce positive result if this is 'greater' than the given

object

int compareTo(Object obj);

}

Trang 41

Obviously, it is up to the implementing class to

decide how to compare two items Let us define the

compareTo method for the class Book and for the

class Entry

Trang 42

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

In the class Book we modify the purpose, but the

header must be the same as defined in the

interface:

// compare the publication year of this book with

the given book

int compareTo(Object obj);

The examples are:

Book b1 = new Book("HtDP", 2000, 55);

Book b2 = new Book("Call of the Wild", 1995,

Trang 43

The template for the method includes this.year Our

goal is to compare it with the field year of the

method argument obj We need to cast obj before

accessing the field year:

// compare the publication year of this book with

the given book

int compareTo(Object obj){

return this.year

-((Book)obj).getPublicationYear();

}

Trang 44

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

For the class Entry the purpose and header

are:

// compare the distance of this run with the distance of the

given run

int compareTo(Object obj);

In the class Entry the examples are as

follows, assuming three Date objects d1,

d2, and d3 have been defined earlier:

Entry e1 = new Entry(d1, 5.0, 25,"Good");

Entry e2 = new Entry(d2, 3.0, 24,"Tired");

Entry e3 = new Entry(d3, 26.0,

156,"Great");

e1.compareTo(e2); // should be > 0      

e2.compareTo(e3); // should be < 0      

e2.compareTo(e2); // should be = 0

Trang 45

The template for the method includes

this.distance Our goal is to compare it

with the field distance of the method

argument obj We need to cast obj before accessing the field distance:

// compare the distance recorded in this entry with the given entry int compareTo(Object obj){

return this.distance

-((Entry)obj).getDistance();

Trang 46

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

Now two lists are identical We can use ALoObjects

to represent the two lists instead.

Trang 47

public abstract class ALoObjects{

public abstract ALoObjects sort();

public abstract ALoObjects

insert(Object b)

}

Trang 48

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

public ALoObjects insert(Object b) {

return new ConsLoObject(obj, this);

}

}

Trang 49

public class ConsLoObject extends ALoObjects {

public ALoObjects sort() {

Trang 50

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

Exercises

Trang 51

Exercise 2.0.7.   Modify the way the class Book

implements the Comparable interface, so that

it compares the books by price Make sure the

sort works correctly. 

Exercise 2.0.8.   Develop the method isSorted

that determines whether a list of Objects that

implement Comparable interface is sorted. 

Exercise 2.0.9.   The class String implements

the Comparable interface to allow the

comparison of strings according to the

lexicographical ordering Modify the class

Book so that the compareTo method compares

the books by their title and then sort the

books in lexicographical order  

Exercise 2.0.10.   Modify the way the class

Entry implements the Comparable interface, so that we can sort the entries by their date.

Trang 52

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

Objects that represent

Functions

Trang 53

• Quay trở lại vấn đề quản lý sách của 1 cửa hàng sách.

• Giả sử bây giờ người quản lý muốn sắp xếp những

cuốn sách trong nhà sách theo từng trình tự nhất

định như: theo thứ tự abc, theo giá bán và theo năm

xuất bản.

Trang 54

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

Find a solution…

• Với 3 tiêu chí trên, chúng ta cần phát triển 3

cách khác nhau để sắp xếp một danh sách

những cuốn sách theo 3 yêu cầu khác nhau

• Cụ thể ở trường hợp này ta phải viết trong

cấu trúc danh sách thêm 3 phương thức để

sắp xếp theo 3 chuẩn tương ứng mà cách

viết cho mỗi phương thức chỉ khác nhau

chút ít Và thật là mất thời gian khi phải viết

đi viết lại những mã nguồn giống nhau Nên

chúng ta cần phải chọn ra cách giải quyết

thích hợp và hiệu quả hơn.

Trang 55

• Đầu tiên chúng ta cần định nghĩa một Interface là

Comparator mà nó chỉ chứa một phương thức để so

sánh hai đối tượng bất kỳ.

interface Comparator {

int compare ( Object obj1 , Object obj2 ) ;

}

Trang 56

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

class ByYear implements Comparator {

// compare two books by the year published

int compare ( Object obj1 , Object obj2 ) {

return (( Book ) obj1 ) year

-(( Book ) obj2 ) year ;

}

}

Trang 57

Compare byPrice

class ByPrice implements Comparator {

// compare two books by price

int compare ( Object obj1 , Object obj2 ){

return (( Book ) obj1 ) price

-(( Book ) obj2 ) price ;

}

}

Trang 58

Course material developed by Mai Anh Tho (tho@hcmuaf.edu.vn)

Compare byTitle

class ByTitle implements Comparator {

// compare two books by title

int compare ( Object obj1 , Object obj2 ){

return (( Book ) obj1 ) title.

compareTo ((( Book ) obj2 ) title ) ;

}

}

Ngày đăng: 16/07/2014, 04:00

TỪ KHÓA LIÊN QUAN

w