I want to restrict or limit update to members palidromes
and palidromesFIFO
to only one method, say addPalindromeWord
, and don't let any other methods to update it. Is there a way to do that?
Target is to achieve modularity in handling the addition of any new value to the collections. Some basic logic has to be followed. I would not like to see any other method DIRECTLY affecting the collections in abstract manner.
static class MyPalindromes{
private Set<String> palidromes;
private Deque<String> palidromesFIFO;
private int maxLenOfCache;
public MyPalindromes(int maxCachingLength) {
palidromes = new TreeSet<>(new MyComparator());
palidromesFIFO = new ArrayDeque<String>();
maxLenOfCache = maxCachingLength;
}
public void addPalindromeWord(String word) {
palidromes.add(word);
if (palidromesFIFO.size() == maxLenOfCache && !palidromesFIFO.isEmpty()) {
palidromesFIFO.removeFirst();
}
if (maxLenOfCache > 0) {
palidromesFIFO.addLast(word);
}
}
public void filterAndAddOnlyPalindromes(List<String> words) {
List<String> validWords = new ArrayList<>();
for (String w : words) {
if (isPalindrome(w)) {
validWords.add(w);
}
}
this.addPalindromeWords(validWords);
}
public void addPalindromeWords(List<String> words) {
for (String word : words) {
// palidromes.add(validWords); //<< DISALLOW this direct update to the set
this.addPalindromeWord(word); // << ONLY allow update through addPalindromeWord method
}
}
}