-
Notifications
You must be signed in to change notification settings - Fork 1
/
FlyeweightCodingExercise.java
61 lines (53 loc) · 1.54 KB
/
FlyeweightCodingExercise.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
Exercise for flyweight section
Given a class Sentence which can take a string such as "hello world"
provide a method getWord() that returns a word token which is used to capitalize a word in a sentence
*/
package structural.flyweight;
import java.util.*;
class Sentence
{
private String plainText;
private String [] words;
private Map<Integer, WordToken> tokens = new HashMap<>();
public Sentence(String plainText)
{
// Create a list of words
words = plainText.split(" ");
}
public WordToken getWord(int index)
{
WordToken wt = new WordToken(); // contains one variable, called capitalize
tokens.put(index, wt);
return tokens.get(index); // return token at that index
}
@Override
public String toString()
{
ArrayList<String> ws = new ArrayList<>();
for(int i = 0; i < words.length; i++)
{
String word = words[i];
// a bit overkill here. we are getting the index in the hash map and checking if it contains the variable capitalize
if(tokens.containsKey(i) && tokens.get(i).capitalize)
{
word = word.toUpperCase();
}
ws.add(word);
}
return String.join(" ", ws);
}
class WordToken
{
public boolean capitalize;
}
}
class FlyweightExerciseDemo
{
public static void main(String[] args)
{
Sentence sentence = new Sentence("hello world");
sentence.getWord(1).capitalize = true;
System.out.println(sentence);
}
}