map实现简单缓存

以下是通过Map实现java缓存的功能:

package cache;

import java.util.HashMap;

public class Cache {

	private HashMap cache;
	
	Cache(){
		cache = new HashMap();
	}
	
	public T get(String key){
		return cache.get(key);
	}
	
	public void put(String key, T value){
		cache.put(key, value);
	}
	
	public void remove(String key){
		cache.remove(key);
	}
	
	public boolean remove(String key, T value){
		return cache.remove(key,value);
	}
	
	public void clear(){
		cache.clear();
	}
	
	public  boolean containtKey(String key){
		return cache.containsKey(key);
	}
}

Cat.java

package cache;

public class Cat {

	private String name;
	
	private String hair;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getHair() {
		return hair;
	}

	public void setHair(String hair) {
		this.hair = hair;
	}
	
	public void catchMouse(){
		System.out.println("一只叫"+this.name+"的"+this.hair + "猫在逮白耗子。");
	}
}

Test.java 

package cache;

public class Test {

	public static void main(String[] args) {
		Cache map = new Cache();
		Cat cat = new Cat();
		cat.setName("Tom");
		cat.setHair("红");
		map.put("1", cat);
		
		Cat cat1 = map.get("1");
		cat1.catchMouse();
	}
}




你可能感兴趣的:(java)