在屏幕中显示一个文本文档,其中相同的字符串“java”共享同一个对象,而这些字符串的颜色和大小可以不同。现使用享元模式设计一个方案实现字符串对象的共享,要求绘制类图并编程实现。
import java.awt.*; import javax.swing.*; public class Client { public static void main(String args[]) { Share_String nd1,nd2,nd3,nd4,nd5; String_Factory df=new String_Factory(); JFrame jf = new JFrame();//窗口 JPanel jp = new JPanel();//面板 jf.setVisible(true); jf.setTitle("享元模式"); jf.setBounds(100, 100, 500, 500); jf.add(jp); nd1=df.get_Sh_string("JAVA"); nd1.use(new Propertyy(15,Color.black,nd1,jp)); nd2=df.get_Sh_string("JAVA"); nd2.use(new Propertyy(22,Color.GREEN,nd2,jp)); nd3=df.get_Sh_string("JAVA"); nd3.use(new Propertyy(25,Color.red,nd3,jp)); } }
import java.awt.Font; import javax.swing.JLabel; public class JJava implements Share_String { private String type; public JJava(String type) { this.type=type; } public String getType() { return this.type; } public void setType(String tmp) { this.type=tmp; } public void use(Propertyy port) { JLabel jl1 = new JLabel(port.getNd1().getType()); Font f = new Font("宋体",Font.PLAIN,port.getZihao()); jl1.setFont(f); jl1.setForeground(port.getColor()); port.getJPanel().add(jl1); } }
import java.awt.Color; import java.awt.Font; import javax.swing.JLabel; import javax.swing.JPanel; public class Propertyy { private int font_size; private Color color; private Share_String str; private JPanel jp; public Propertyy(int font_size,Color color, Share_String str,JPanel jp) { this.color=color; this.font_size=font_size; this.str=str; this.jp=jp; } public int getZihao() { return this.font_size; } public Color getColor() { return this.color; } public Share_String getNd1() { return this.str; } public JPanel getJPanel() { return this.jp; } }
public interface Share_String { public String getType(); public void use(Propertyy port); }
import java.util.*; public class String_Factory { private ArrayList strs = new ArrayList(); public String_Factory() { Share_String nd1=new JJava("JAVA"); strs.add(nd1); } public Share_String get_Sh_string(String type) { if(type.equalsIgnoreCase("JAVA")) { return (Share_String)strs.get(0); } else { return null; } } public int getTotalDevice() { return strs.size(); } }
享元模式的关键在于return object。返回的是类似C语言的指针,不会重复开辟空间复制一个对象返回。