SingleCache.java

56 lines | 1.357 kB Blame History Raw Download
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufrgs.inf.prosoft.memoizeit.cache;

/**
 *
 * @author romulo
 */
public class SingleCache implements Cache {

    private final CachingPerformance cachingPerformance;
    private String lastInput;
    private Object result;

    public SingleCache() {
        this.cachingPerformance = new CachingPerformance();
    }

    public SingleCache(CachingPerformance cachingPerformance) {
        this.cachingPerformance = cachingPerformance;
    }

    public CachingPerformance getCachingPerformance() {
        return this.cachingPerformance;
    }

    @Override
    public Object put(String key, Object value) {
        this.lastInput = key;
        this.result = value;
        this.cachingPerformance.registerSize(1);
        return this.result;
    }

    @Override
    public Object get(Object key) {
        if (key.equals(this.lastInput)) {
            this.cachingPerformance.registerHit();
            return this.result;
        }
        this.cachingPerformance.registerMiss();
        return null;
    }

    @Override
    public void invalidate(String key) {
        this.lastInput = null;
        this.result = null;
        this.cachingPerformance.registerInvalidation();
    }

}