singleton and inheritance in Java

前端 未结 6 600
鱼传尺愫
鱼传尺愫 2021-01-17 16:30

I have a base class that captures some functionality common to two classes. In other words, I can create one base class and make these two classes subclasses of that base cl

6条回答
  •  执笔经年
    2021-01-17 16:54

    I had a similar requirement: I had multiple cache maps with repeating methods and members, so I've created an abstract class like:

    public abstract class AbstractCache {
    
        protected final Map cache;
    
        protected AbstractCache() {
            this.cache = getDefaultExpiringMap(TimeUnit.HOURS.toMillis(4));
        }
    
        public Map getCache() {
            return cache;
        }
    
        public T getAll(String id) {
            return cache.get(id);
        }
    }
    

    Then I've extended this class and created a singleton instance:

    public final class FooCache extends AbstractCache> {
    
        public static final FooCache INSTANCE = new FooCache();
    
        private FooCache() {
            super();
        }
    
        public void add(String fooId, Integer value) {
            cache.computeIfAbsent(fooId, k -> new HashSet<>()).add(value);
        }
    }
    

    And the usage:

    public static void main(String[] args) {
        FooCache.INSTANCE.add("a", 1);
        System.out.println(FooCache.INSTANCE.getAll("a"));
    }
    

提交回复
热议问题