【问题标题】:Restrict access to a instance variable to only selected method in that class限制对实例变量的访问仅限于该类中的选定方法
【发布时间】:2021-01-23 05:23:12
【问题描述】:

我想限制或限制对成员palidromespalidromesFIFO 的更新仅限于一种方法,例如addPalindromeWord,并且不要让任何其他方法更新它。有没有办法做到这一点?

目标是在处理向集合添加任何新值时实现模块化。必须遵循一些基本逻辑。我不希望看到任何其他以抽象方式直接影响集合的方法。

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
        }
    }
}

【问题讨论】:

    标签: java oop access-control system-design


    【解决方案1】:

    您可以将您的集合“嵌套”在仅公开这些方法的专用(可选内部)class 中。那么外部类就不能访问私有字段和方法了,你的Collection就被其他方式修改保存了。

    但是,您还必须确保不返回 Collection,否则开发人员可以直接对其进行修改。通过从内部类中的集合委派任何纯读取操作来做到这一点。

    如果你这样做'足够通用',你只需要一堆类来处理这个。在周围建立一个小型图书馆实际上是一件好事。

    【讨论】:

    猜你喜欢
    • 2011-02-07
    • 2012-02-15
    • 1970-01-01
    • 2014-06-25
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 2010-11-08
    • 2011-05-09
    相关资源
    最近更新 更多