napisałam sobie dzisiaj kasę-bazę zwierząt i metodę getNextAnimal()
- chcę wybierać zwierzątko według algorytmu, który sobie wybiorę (np. od początku, od końca, losowo, największe / najstarsze na początku itd... ). Na siłę można byłoby to zaimplementować w bazie, ale wydaje mi się, że ładniejsze rozwiązaniee to przekazywanie algorytmu do bazy. Z jakim wzorcem powinnam sie zapoznać lub jak to ładnie implementować? poniżej na uproszczonym przykładzie, napisałam coś takiego (2 algorytmy do wyboru) ale jest chyba trochę słabe ;\ ( np nie mogę tworzyć bazy z konstruktorem tj - DataBase dataBase = new DataBase(new FromTheBeginning(dataBase));
import java.util.*;
class DataBase {
private List<String> animals;
private AnimalChooser animalChooser;
public DataBase() {
animals = new ArrayList<String>();
animalChooser = new FromTheBeginning(this);
}
void setAnimalChooser(AnimalChooser animalChooser) {
this.animalChooser = animalChooser;
}
void add(String animal) {
animals.add(animal);
}
public String getNextAnimal() {
return animalChooser.getNext();
}
public List<String> list() {
return animals;
}
}
interface AnimalChooser {
public String getNext();
}
class RandomChooser implements AnimalChooser {
private Random randomGenerator;
private DataBase dataBase;
public RandomChooser(DataBase dataBase) {
this.dataBase = dataBase;
randomGenerator = new Random();
}
@Override
public String getNext() {
List<String> animals = dataBase.list();
int index = randomGenerator.nextInt(animals.size());
return animals.get(index);
}
}
class FromTheBeginning implements AnimalChooser {
private int nextId = 0;
private DataBase dataBase;
FromTheBeginning(DataBase dataBase) {
this.dataBase = dataBase;
}
@Override
public String getNext() {
List<String> animals = dataBase.list();
if(nextId >= animals.size())
nextId = 0;
return dataBase.list().get(nextId++);
}
}
public class Main {
public static void main(String[] args) {
DataBase dataBase = new DataBase();
dataBase.add("kot");
dataBase.add("lew");
dataBase.add("wydra");
for(int i = 5; i > 0; --i)
System.out.println(dataBase.getNextAnimal());
dataBase.setAnimalChooser(new RandomChooser(dataBase));
for(int i = 5; i > 0; --i)
System.out.println(dataBase.getNextAnimal());
}
}