num14---享元模式
Posted dxxdsw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了num14---享元模式相关的知识,希望对你有一定的参考价值。
案例:
public abstract class WebSite { public abstract void use(User user);//抽象方法 }
public class ConcreteWebSite extends WebSite { private String type = ""; //网站发布形式(类型) public ConcreteWebSite(String type) { this.type = type; } @Override public void use(User user) { System.out.println("网站发布形式:" + type + " 使用者:" + user.getName()); } }
public class User { private String name; public User(String name) { super(); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
// 网站工厂类 public class WebSiteFactory { //集合,充当池的作用 private HashMap<String, ConcreteWebSite> pool = new HashMap<>(); //根据网站类型返回网站 public WebSite getWebSiteCategory(String type) { if(!pool.containsKey(type)) { pool.put(type, new ConcreteWebSite(type)); } return (WebSite)pool.get(type); } //获取池中数量 public int getWebSiteCount() { return pool.size(); } }
public static void main(String[] args) { // 创建一个工厂类 WebSiteFactory factory = new WebSiteFactory(); WebSite webSite1 = factory.getWebSiteCategory("新闻"); webSite1.use(new User("tom")); WebSite webSite2 = factory.getWebSiteCategory("博客"); webSite2.use(new User("jack")); WebSite webSite3 = factory.getWebSiteCategory("博客"); webSite3.use(new User("smith")); WebSite webSite4 = factory.getWebSiteCategory("博客"); webSite4.use(new User("king")); System.out.println("容量=" + factory.getWebSiteCount()); }
以上是关于num14---享元模式的主要内容,如果未能解决你的问题,请参考以下文章