Reputation: 67
I have a pretty simple problem with Java, but explaining it is not a simple as i expected. Basically, I want to check if any objects from a certain class exist. An example:
I have a class Animal, and I have two subclasses, Cat and Dog. And when running the program, I want to know if any dogs or cats exist. I know I created a dog, OR a cat, but I don't know which. I could check all cats and dogs that I created in my previous code if they exist or not, but it's not only an ugly, but also a dumb solution.
So, is there a nice way to know if there are any dogs or cats that currently exist?
Thanks in advance!
Upvotes: 1
Views: 190
Reputation: 2877
Solution using the factory DP :
public class DogFactory {
private int producedDogsCount;
public DogFactory() {
this.producedDogsCount = 0;
}
public Dog produceDog() {
this.producedDogsCount++;
return new Dog();
}
public int getProducedDogsCount() {
return this.producedDogsCount;
}
}
Then to produce dogs you need the factory :
DogFactory dogFactory = new DogFactory();
and need to call the produceDog()
method :
Dog myDog = dogFactory.produceDog();
In order to know how many dogs you have produced you ask the dog factory :
int producedDogsCount = dogFactory.getProducedDogsCount();
Note that this allows you to have different counters depending on the characteristics of the dogs you produce (for instance if your factory allows you to choose the color, race, character, size of the dog to be produced)
Upvotes: 0
Reputation: 196
Here's a real simple approach...
Assuming Cats and Dogs never die (as my children would wish), then each class can have a static counter.
class Dog extends Animal {
private static int liveOnes = 0;
public Dog() {
liveOnes++;
}
public static int getHowManyAlive() { return liveOnes; }
}
You can then check if any dogs exist by using
Dog.getHowManyAlive() > 0
If they do die, then you need to explicitly kill them and decrement the count.
Upvotes: 3