如果大量对象只是某些细节不同,则可将这些不同抽离到外部,将相同的作为共享.那些不同的可作为参数传递.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package flyweight;
public class User { private String name;
public User(String name) { this.name = name; }
public String getName() { return name; }
public void setName(String name) { this.name = name; } }
|
1 2 3 4 5 6 7 8 9
| package flyweight;
public abstract class Website { public abstract void option(User user); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| package flyweight;
public class ConcreteWebsite extends Website { private String type;
public ConcreteWebsite(String type) { this.type = type; }
@Override public void option(User user) { System.out.println("网站类型: " + type + ", 用户: " + user.getName()); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package flyweight;
import java.util.concurrent.ConcurrentHashMap;
public class WebsiteFactory { private ConcurrentHashMap<String, ConcreteWebsite> webs = new ConcurrentHashMap<>(5);
public ConcreteWebsite getWebsite(String type) { if (webs.get(type) == null) webs.put(type, new ConcreteWebsite(type)); return webs.get(type); }
public int capacity() { return webs.size(); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| package flyweight;
public class Main { public static void main(String[] args) { WebsiteFactory factory = new WebsiteFactory(); User 小明 = new User("小明"); ConcreteWebsite blog = factory.getWebsite("博客"); blog.option(小明);
User 小红 = new User("小红"); ConcreteWebsite community = factory.getWebsite("社区"); community.option(小红);
User 如花 = new User("如花"); ConcreteWebsite blog2 = factory.getWebsite("博客"); blog2.option(如花);
System.out.println(factory.capacity()); } }
|
