public class CountingDuckFactory implements AbstractDuckFactory {
@Override
public Quackable createMallardDuck() {
return new QuackCounter(new MallardDuck());
}
@Override
public Quackable createRedheadDuck() {
return new QuackCounter(new RedheadDuck());
}
@Override
public Quackable createDuckCall() {
return new QuackCounter(new DuckCall());
}
@Override
public Quackable createRubberDuck() {
return new QuackCounter(new RubberDuck());
}
}
public class CountingDuckFactory implements AbstractDuckFactory {
- This declares a public class named
CountingDuckFactory
.
- It implements the
AbstractDuckFactory
interface, indicating that instances of this class can create different types of ducks.
@Override public Quackable createMallardDuck() { return new QuackCounter(new MallardDuck()); }
- This method is part of the
AbstractDuckFactory
interface implementation.
- It creates and returns a new instance of
QuackCounter
wrapped around a MallardDuck
, representing the creation of a Mallard duck with counting functionality.
@Override public Quackable createRedheadDuck() { return new QuackCounter(new RedheadDuck()); }
- This method is part of the
AbstractDuckFactory
interface implementation.
- It creates and returns a new instance of
QuackCounter
wrapped around a RedheadDuck
, representing the creation of a Redhead duck with counting functionality.
@Override public Quackable createDuckCall() { return new QuackCounter(new DuckCall()); }
- This method is part of the
AbstractDuckFactory
interface implementation.
- It creates and returns a new instance of
QuackCounter
wrapped around a DuckCall
, representing the creation of a Duck Call with counting functionality.
@Override public Quackable createRubberDuck() { return new QuackCounter(new RubberDuck()); }
- This method is part of the
AbstractDuckFactory
interface implementation.
- It creates and returns a new instance of
QuackCounter
wrapped around a RubberDuck
, representing the creation of a Rubber duck with counting functionality.
}
- Closes the
CountingDuckFactory
class.
- Overall Explanation:
- The
CountingDuckFactory
class is an implementation of the AbstractDuckFactory
interface.
- It provides concrete implementations for creating different types of ducks (Mallard, Redhead, Duck Call, Rubber Duck), each wrapped with a
QuackCounter
to add counting functionality.
- The counting functionality allows tracking the total number of quacks across all ducks created by this factory.
- This class is used in the
DuckSimulator
to create ducks with counting functionality. It demonstrates the use of the Abstract Factory pattern, where a family of related or dependent objects is created without specifying their concrete classes.