public class RubberDuck implements Quackable {
Observable observable;
public RubberDuck() {
observable = new Observable(this);
}
public void quack() {
System.out.println("Squeak");
notifyObservers();
}
public void registerObserver(Observer observer) {
observable.registerObserver(observer);
}
public void notifyObservers() {
observable.notifyObservers();
}
@Override
public String toString() {
return "Rubber Duck";
}
}
public class RubberDuck implements Quackable {
- This declares a public class named
RubberDuck
.
- It implements the
Quackable
interface, indicating that instances of this class can quack.
Observable observable;
- This declares a member variable named
observable
of type Observable
.
- It is used to manage observers interested in the quacking events of this rubber duck.
public RubberDuck() { observable = new Observable(this); }
- This is the constructor of the
RubberDuck
class.
- It initializes the
observable
variable with a new instance of Observable
, passing itself (this
) as the QuackObservable
object.
public void quack() { System.out.println("Squeak"); notifyObservers(); }
- This method is part of the
Quackable
interface implementation.
- It outputs "Squeak" to the console, simulating the squeaking sound of a rubber duck, and then notifies observers.
public void registerObserver(Observer observer) { observable.registerObserver(observer); }
- This method is part of the
Quackable
interface implementation.
- It delegates the responsibility of registering observers to the
Observable
object.
public void notifyObservers() { observable.notifyObservers(); }
- This method is part of the
Quackable
interface implementation.
- It delegates the responsibility of notifying observers to the
Observable
object.
@Override public String toString() { return "Rubber Duck"; }
- This overrides the
toString
method to provide a custom string representation of the object.
}
- Closes the
RubberDuck
class.
- Overall Explanation:
- The
RubberDuck
class represents a rubber duck object that can quack.
- It implements the
Quackable
interface, providing methods for quacking, registering observers, and notifying observers.
- The
observable
member variable is used to manage observers interested in the quacking events of the rubber duck.
- The
toString
method provides a descriptive string representation of the object, returning "Rubber Duck".
- This class is part of the larger design that allows different types of ducks and quackable entities to be treated uniformly in the code.