[英]What is the difference between Flyweight design pattern and Java cache
[英]Flyweight design pattern in java, what is the purpose?
我有以下代码:
public class Sentence {
private String [] words;
private Map<Integer, WordToken> tokens = new HashMap<>();
public Sentence(String plainText) {
words = plainText.split(" ");
}
public WordToken getWord(int index) {
WordToken wt = new WordToken();
tokens.put(index, wt);
return tokens.get(index);
}
@Override
public String toString() {
List<String> ws = new ArrayList<>();
for (int i = 0; i < words.length; ++i) {
String w = words[i];
if (tokens.containsKey(i) && tokens.get(i).capitalize) {
w = w.toUpperCase();
}
ws.add(w);
}
return String.join(" ", ws);
}
}
并测试:
@Test
public void test() {
Sentence s = new Sentence("alpha beta gamma");
s.getWord(1).capitalize = true;
assertEquals("alpha BETA gamma", s.toString());
}
我的问题是:以这种方式使用享元模式的目的是什么?
Flyweight 模式是一种重用模式,它通过重用相同的对象来减少程序的内存占用。 这对于表示简单值(例如单词)的值对象很常见,因为具有相同字符的单词是相同的。 例如,假设我们有以下句子(暂时忽略大小写):
the doorman held the door for the guest
这句话有 39 个字符,这意味着如果我们从这句话创建一个String
,我们将需要存储 39 个字符(暂时忽略 Java String
实现使用的length
字段)。 如果我们看一下这句话,也有3个实例the
,它们彼此相同。 还有7个空格,它们彼此相同。 如果我们对字符串进行标记,我们将获得以下单词:
["the", "doorman", "held", "the", "door", "for", "the", "guest"]
如果我们只取这个列表中的唯一值,我们得到:
["the", "doorman", "held", "door", "for", "guest"]
使用这些独特的词,我们可以通过将句子中的词的索引映射到独特的词来创建句子:
[0, 1, 2, 0, 3, 4, 0, 5]
为了重建句子,我们将上面的索引简单地映射到唯一词的列表,在每个词之间添加一个空格。
在您提供的示例中,该算法似乎不正确(它不节省任何空间,因为它同时存储了单词和标记)。 更正确的解决方案(众多解决方案之一)类似于):
public class Sentence {
private final List<Integer> wordMap = new ArrayList<>();
private final List<String> words = new ArrayList<>();
public Sentence(String sentence) {
for (String word: sentence.split(" ")) {
addIfNotExists(word);
wordMap.add(words.indexOf(word));
}
}
private void addIfNotExists(String word) {
if (!words.contains(word)) {
words.add(word);
}
}
public List<Integer> getWordMap() {
return wordMap;
}
public List<String> getWords() {
return words;
}
public static void main(String[] args) {
Sentence s = new Sentence("the doorman held the door for the guest");
System.out.println(s.getWordMap());
System.out.println(s.getWords());
}
}
运行此结果会产生以下输出:
[0, 1, 2, 0, 3, 4, 0, 5]
[the, doorman, held, door, for, guest]
我把它留给你来实现toString
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.