public class QuackCounter implements Quackable {
Quackable duck;
static int numberOfQuacks;
public QuackCounter(Quackable duck) {
this.duck = duck;
}
public void quack() {
duck.quack();
numberOfQuacks++;
}
public static int getQuacks() {
return numberOfQuacks;
}
public void registerObserver(Observer observer) {
duck.registerObserver(observer);
}
public void notifyObservers() {
duck.notifyObservers();
}
}
public class QuackCounter implements Quackable {
- This declares a public class named
QuackCounter.
- It implements the
Quackable interface, indicating that instances of this class can quack.
Quackable duck;
- This declares a member variable named
duck of type Quackable.
- It is used to store the quackable entity that this
QuackCounter is wrapping.
static int numberOfQuacks;
- This declares a static member variable named
numberOfQuacks of type int.
- It will be used to count the number of quacks across all instances of
QuackCounter. Being static means it is shared among all instances of the class.
public QuackCounter(Quackable duck) { this.duck = duck; }
- This is the constructor of the
QuackCounter class.
- It takes a
Quackable object as a parameter and initializes the duck variable with it.
public void quack() { duck.quack(); numberOfQuacks++; }
- This method is part of the
Quackable interface implementation.
- It calls the
quack method on the wrapped duck object, effectively delegating the quacking behavior. After quacking, it increments the numberOfQuacks.
public static int getQuacks() { return numberOfQuacks; }
- This is a static method that allows access to the
numberOfQuacks variable.
- It returns the total number of quacks across all instances of
QuackCounter.
public void registerObserver(Observer observer) { duck.registerObserver(observer); }
- This method is part of the
Quackable interface implementation.
- It delegates the responsibility of registering observers to the wrapped
duck object.
public void notifyObservers() { duck.notifyObservers(); }
- This method is part of the
Quackable interface implementation.
- It delegates the responsibility of notifying observers to the wrapped
duck object.
}
- Closes the
QuackCounter class.
- Overall Explanation:
- The
QuackCounter class is a decorator that wraps around a Quackable object to count the number of quacks.
- It implements the
Quackable interface, providing methods for quacking, registering observers, and notifying observers.
- The
quack method delegates the quacking behavior to the wrapped duck and increments the numberOfQuacks.
- The
getQuacks method allows retrieving the total number of quacks across all instances of QuackCounter.
- This class is part of the larger design that allows counting the quacks of different types of ducks and quackable entities.