/**
* 缓存实例的不可变类
* @author RZL
*
*/
public class ImmutaleCache {
private static int MAX_SIZE = 10;
private static ImmutaleCache[] cache = new ImmutaleCache[MAX_SIZE];
private static int pos = 0;
private final Person person;
private ImmutaleCache(Person person){
this.person = person;
}
public Person getPerson() {
return person;
}
public static ImmutaleCache valueOf(Person person){
//遍历已缓存的对象
for(int i = 0; i < MAX_SIZE; i++){
//如果已有相同实例,直接返回该缓存实例
if(cache[i] != null && cache[i].getPerson().equals(person)){
return cache[i];
}
}
//如果缓存中没有且缓存已满
if(pos >= MAX_SIZE){
cache[0] = new ImmutaleCache(person);
pos = 1;
}else{
cache[pos++] = new ImmutaleCache(person);
}
return cache[pos-1];
}
public boolean equals(Object obj) {
if(this == obj){
return true;
}
if(obj!= null && obj.getClass() == ImmutaleCache.class){
ImmutaleCache ic = (ImmutaleCache)obj;
return person.equals(ic.getPerson());
}
return false;
}
//重写hashCode方法是为了维护常规协议,该协议声明相等的对象具有相等的hash值
public int hashCode() {
return person.hashCode();
}
//........................main..............................
public static void main(String[] args) {
Name name1 = new Name("zhiliang","rui");
Name name2 = new Name("zhiliang","rui");
Person rzl = new Person(name1);
Person me = new Person(name2);
ImmutaleCache ic1 = ImmutaleCache.valueOf(rzl);
ImmutaleCache ic2 = ImmutaleCache.valueOf(me);
System.out.println(ic1==ic2);
}
//..........................................................
}
class Person {
private final Name name;
public Person(Name name) {
//相当于值传递而不是引用传递,防止修改传入的Name对象而修改Person对象
this.name = new Name(name.getFirstName(), name.getLastName());
}
public Name getName() {
//返回一个匿名对象,该对象是原对象的一个副本,防止获取到Name对象引用后修改该对象而修改Person对象
return new Name(name.getFirstName(), name.getLastName());
}
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object != null && object.getClass() == Person.class) {
Person p = (Person) object;
return name.equals(p.getName());
}
return false;
}
public int hashCode() {
return name.hashCode();
}
}
class Name {
private String firstName;
private String lastName;
public Name() {
}
public Name(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj != null && obj.getClass() == Name.class) {
Name temp = (Name) obj;
if (firstName.equals(temp.getFirstName())
&& lastName.equals(temp.getLastName())) {
return true;
}
}
return false;
}
@Override
public int hashCode() {
return firstName.hashCode()+lastName.hashCode()*17;
}
}
缓存不可变类实例的不可变类【参考疯狂Java讲义】
最新推荐文章于 2024-08-28 20:58:28 发布