编写享元类package 享元模式;
public class Word {
private String key;
private String content;
public Word(String key, String content) {
super();
this.key = key;
this.content = content;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return this.key+":"+this.content;
}
}
package 享元模式;
import java.security.Policy;
import java.util.HashMap;
public class WordPool {
private static HashMap pool = new HashMap();
public static Word getWord(String key,String content){
Word word = (Word)pool.get(key);
if(word==null){
word = new Word(key, content);
pool.put(key, word);
}
return word;
}
}
Flyweight.java
package 享元模式;
import java.util.HashMap;
public class Flyweight {
public static void main(String[] args) {
Word w1 = WordPool.getWord("刘德华","001");
Word w2 = WordPool.getWord("张学友","002");
Word w3 = WordPool.getWord("刘德华","002");
Word w4 = WordPool.getWord("刘德华","004");
System.out.println(w4);
}
}
274



被折叠的 条评论
为什么被折叠?



