享元是共享对象的意思,用来解决重复对象的内存浪费的问题。缓冲池就是为了共享对象而出现的一种技术,常见的使用池技术的场景有String常量池、数据库连接池、缓冲池等。
『享』共享,『元』对象;
典型的共享技术——对象池,典型的对象池——String常量池,数据库连接池;
// 享元接口
public interface Website {
void use(User user);
}
// 享元具体类
public class ConcreteWebsite implements Website {
private String type;
public ConcreteWebsite(String type) {
this.type = type;
}
@Override
public void use(User user) {
System.out.println("网站的发布形式: " + type + ", 在使用中");
}
}
public class WebsiteFactory {
private Map<String, Website> sitePool = new HashMap<>();
// 根据网站的类型返回一个网站,如果没有就创建一个网站,并放到池中并返回
public Website getWebsiteByType(String type) {
if (!sitePool.containsKey(type))
sitePool.put(type, new ConcreteWebsite(type));
return sitePool.get(type);
}
// 获取网站类型总数
public int getWebsiteCount() {
return sitePool.size();
}
}
public class Client {
public static void main(String[] args) {
WebsiteFactory websiteFactory = new WebsiteFactory();
Website site1 = websiteFactory.getWebsiteByType("新闻");
site1.use(new User("Tom"));
Website site2 = websiteFactory.getWebsiteByType("财经");
site2.use(new User("Lucy"));
Website site3 = websiteFactory.getWebsiteByType("财经");
site3.use(new User("John"));
Website site4 = websiteFactory.getWebsiteByType("财经");
site4.use(new User("Baden"));
}
}
website release: news, in using
website release: finance, in using
website release: finance, in using
website release: finance, in using
All category in websites sum up to => 2 kinds
Process finished with exit code 0