Chương 5: Từ một đến nhiều: Singleton và Flyweight mẫu giống như cách bạn đã làm với độc thân. Bạn có thể tạo ra các đối tượng flyweight khi lớp đầu tiên được nạp, thực hiện xây dựng tư nhân, và cho phép tạo đối tượng chỉ thông qua một phương pháp getInstance: | 113 Chapter 5 From One to Many The Singleton and Flyweight Patterns the same way you did with singletons. You can create the flyweight object when the class is first loaded make the constructor private and allow object creation only through a getInstance method public class StudentThreaded String name int id int score double averageScore private static StudentThreaded singleObject new StudentThreaded private StudentThreaded public void setAverageScore double a averageScore a public void setName String n name n public void setId int i id i public void setScore int s score s public String getName return name public int getID return id public int getScore return score 114 Part I Getting to Know Patterns__ public double getstanding return double score averagescore - public static StudentThreaded getInstance return singleObject This code puts to work this new version of the flyweight by creating a student object and accessing it both from the main thread and a worker thread. public class TestFlyweightThreaded implements Runable Thread thread public static void main string args TestFlyweightThreaded t new TestFlyweightThreaded public TestFlyweightThreaded String names Ralph Alice Sam int ids 1001 1002 1003 int scores 45 55 65 double total 0 for int loopindex 0 loopindex loopIndex total scores loopindex double averageScore total StudentThreaded student averageScore Ralph 1002 45 thread new Thread this second Name Chapter 5 From One to Many The Singleton and Flyweight Patterns 115 Standing public void run StudentThreaded student Name Standing Running this code gives you this result where you re clearly .