For this problem you must define a simple interface NumTrackerInterface and two implementations of the interface, Tracker1 and Tracker2.
a. Define a Java interface named NumTrackerInterface. A class that implements this interface must keep track of both the sum and the count of numbers that are submitted to it through its add method, and provide getters for the sum, the count, and the average of those numbers. The add method should accept an argument of type int, the getSum and getCount methods should both return values of type int, and the getAverage method should return a value of type double. Suppose a class named Tracker1 implements the NumTrackerInterface. A simple application that uses Tracker1 is shown here. Its output would be "3 29 9.67"
A) package List;
interface NumTrackerInterface {
void add(int n);
int getCount();
int getSum();
double getAverage();
}
class Tracker1 implements NumTrackerInterface {
int count, sum;
double avg;
@Override
public void add(int n) {
count = count + 1;
sum = sum + n;
avg = sum * 1.0/count;
}
@Override
public int getCount() {
return count;
}
@Override
public int getSum() {
return sum;
}
@Override
public double getAverage() {
return Math.round(avg * 100.0) / 100.0;
}
public class Sample {
public static void main (String[] args) {
NumTrackerInterface nt = new Tracker1();
nt.add(5);
nt.add(15);
nt.add(9);
System.out.println(nt.getCount() + " ");
System.out.println(nt.getSum() + " ");
System.out.println(nt.getAverage());
}
}
'공부 > Object-Oriented Design Pattern' 카테고리의 다른 글
CORBA (Common Object Request Broker Architecture)란 (0) | 2022.07.12 |
---|---|
Bridge Pattern 브릿지 패턴이란 (0) | 2021.06.04 |
Builder Pattern 빌더 패턴이란 (0) | 2021.06.01 |
퍼사드 패턴 vs 빌더 패턴 차이점 (0) | 2021.06.01 |
Memento Pattern (메멘토 패턴)이란 (0) | 2021.05.28 |
댓글