當一個應用中使用了大量的對象,這些對象造成了很大的存儲開銷,而對象的大部分狀態或參數都是相同(內部狀態)的時候,可以考慮使用享元模式,使用享元模式可以是這些對象引用都共享相同的實例,降低存儲開銷,而對象之間的不同的狀態參數(外部狀態)則使用外部參數傳入來實現。
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作為外部參數傳入。
