字串內容共享,顏色字型可變(享元模式)
阿新 • • 發佈:2018-12-24
問題
對於內容相同的字串如“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);
}
}