问题
对于内容相同的字符串如“student”能够为多个使用者所共享,而这些字符串的颜色和字体可以不同。设计一个方案能支持字符串的共享,同时还支持批量设置颜色或字体。
解决方案
享元模式
分析:字符串可以放在池子里,保证字符串唯一,与颜色、字体类分别关联,让用户设置颜色、字体。
UML类图
源代码
package task1;
import java.util.ArrayList;
public class WordFactory {
//字符串集合,所有字符串都放在这个集合里面
private ArrayList<String> list = new ArrayList<String>();
private ArrayList<Word> wordList = new ArrayList<Word>();
public Word getWord(String str) {
if(list.contains(str) == false) {
list.add(str);
}
Word word = new Word(str);
wordList.add(word);
return word;
}
//批量设置颜色
public void setColor(Color color) {
for(Word word : wordList) {
word.setColor(color);
}
}
//批量设置字体
public void setFont(Font font) {
for(Word word : wordList) {
word.setFont(font);
}
}
}
package task1;
public class Word {
private String str;
private String font = "Arial";//默认字体
private String color = "Black";//默认颜色
public Word(String str) {
this.str = str;
}
public void setColor(Color color) {
this.color = color.getColor();
}
public void setFont(Font font) {
this.font = font.getFont();
}
@Override
public String toString() {
return "Word [str=" + str + ", font=" + font + ", color=" + color + "]";
}
}
package task1;
public class Color {
private String color;
public Color(String color) {
this.color = color;
}
public String getColor() {
return this.color;
}
}
package task1;
public class Font {
private String font;
public Font(String font) {
this.font = font;
}
public String getFont() {
return this.font;
}
}
测试及结果
package task1;
public class Client {
public static void main(String[] args) {
WordFactory factory = new WordFactory();
Word w1,w2,w3;
w1 = factory.getWord("hello");
w2 = factory.getWord("hello");
w3 = factory.getWord("hello");
System.out.println(w1);
System.out.println(w2);
System.out.println(w3);
System.out.println("---------------------------------------------------");
factory.setColor(new Color("purple"));
factory.setFont(new Font("Tahoma"));
System.out.println(w1);
System.out.println(w2);
System.out.println(w3);
System.out.println("---------------------------------------------------");
w1.setColor(new Color("red"));
w1.setFont(new Font("font1"));
w2.setColor(new Color("green"));
w2.setFont(new Font("font2"));
w3.setColor(new Color("blue"));
w3.setFont(new Font("font3"));
System.out.println(w1);
System.out.println(w2);
System.out.println(w3);
}
}