当一个应用中使用了大量的对象,这些对象造成了很大的存储开销,而对象的大部分状态或参数都是相同(内部状态)的时候,可以考虑使用享元模式,使用享元模式可以是这些对象引用都共享相同的实例,降低存储开销,而对象之间的不同的状态参数(外部状态)则使用外部参数传入来实现。
package flyweight; public abstract class WebSite { protected String type; public WebSite(String type) { this.type = type; } public String getType() { return type; } public abstract void use(User user); } package flyweight; public class ConcurrentWebSite extends WebSite { public ConcurrentWebSite(String type) { super(type); } @Override public void use(User user) { System.out.println("The web site's type is: " + type); System.out.println("User: " + user.getUserName()); System.out.println("Passwd: " + user.getPassWd()); System.out.println(); } } package flyweight; import java.util.HashMap; import java.util.Map; public class WebSiteFactory { private static Map<String, WebSite> webSites = new HashMap<String, WebSite>(); private WebSiteFactory() {} public static WebSite createWebSite(String type) { WebSite webSite = webSites.get(type); if (webSite == null) { webSite = new ConcurrentWebSite(type); webSites.put(type, webSite); } return webSite; } public static int webSitesCount() { return webSites.size(); } } package flyweight; public class User { private String userName; private String passWd; public User(String userName, String passWd) { this.userName = userName; this.passWd = passWd; } public String getUserName() { return userName; } public String getPassWd() { return passWd; } } package flyweight; public class Test { public static void main(String[] args) { WebSite wb1 = WebSiteFactory.createWebSite("BusinessWebSite"); User user1 = new User("root", "root"); wb1.use(user1); WebSite wb2 = WebSiteFactory.createWebSite("BusinessWebSite"); User user2 = new User("admin", "admin"); wb2.use(user2); WebSite wb3 = WebSiteFactory.createWebSite("BusinessWebSite"); User user3 = new User("slave", "slave"); wb3.use(user3); WebSite wb4 = WebSiteFactory.createWebSite("PersonalWebSite"); User user4 = new User("person", "person"); wb4.use(user4); WebSite wb5 = WebSiteFactory.createWebSite("PersonalWebSite"); User user5 = new User("alexis", "alexis"); wb5.use(user5); WebSite wb6 = WebSiteFactory.createWebSite("PersonalWebSite"); User user6 = new User("shadow", "shadow"); wb6.use(user6); System.out.println("WebSites Instances Count: " + WebSiteFactory.webSitesCount()); } }
输出
The web site's type is: BusinessWebSite
User: root
Passwd: rootThe web site's type is: BusinessWebSite
User: admin
Passwd: adminThe web site's type is: BusinessWebSite
User: slave
Passwd: slaveThe web site's type is: PersonalWebSite
User: person
Passwd: personThe web site's type is: PersonalWebSite
User: alexis
Passwd: alexisThe web site's type is: PersonalWebSite
User: shadow
Passwd: shadowWebSites Instances Count: 2
这里我们共享的实例就是WebSite,type为内部参数,User作为外部参数传入。