一、需求:

image.png

二、基本介绍

image.png
image.png

三、代码

  1. public abstract class WebSite {
  2. public abstract void use(User user);//抽象方法
  3. }
  1. //具体网站
  2. public class ConcreteWebSite extends WebSite {
  3. //共享的部分,内部状态
  4. private String type = ""; //网站发布的形式(类型)
  5. //构造器
  6. public ConcreteWebSite(String type) {
  7. this.type = type;
  8. }
  9. @Override
  10. public void use(User user) {
  11. // TODO Auto-generated method stub
  12. System.out.println("网站的发布形式为:" + type + " 在使用中 .. 使用者是" + user.getName());
  13. }
  14. }
  1. public class User {
  2. private String name;
  3. public User(String name) {
  4. super();
  5. this.name = name;
  6. }
  7. public String getName() {
  8. return name;
  9. }
  10. public void setName(String name) {
  11. this.name = name;
  12. }
  13. }
  1. // 网站工厂类,根据需要返回压一个网站
  2. public class WebSiteFactory {
  3. //集合, 充当池的作用
  4. private HashMap<String, ConcreteWebSite> pool = new HashMap<>(16);
  5. //根据网站的类型,返回一个网站, 如果没有就创建一个网站,并放入到池中,并返回
  6. public WebSite getWebSiteCategory(String type) {
  7. if(!pool.containsKey(type)) {
  8. //就创建一个网站,并放入到池中
  9. pool.put(type, new ConcreteWebSite(type));
  10. }
  11. return (WebSite)pool.get(type);
  12. }
  13. //获取网站分类的总数 (池中有多少个网站类型)
  14. public int getWebSiteCount() {
  15. return pool.size();
  16. }
  17. }
  1. public class Client {
  2. public static void main(String[] args) {
  3. // TODO Auto-generated method stub
  4. // 创建一个工厂类
  5. WebSiteFactory factory = new WebSiteFactory();
  6. // 客户要一个以新闻形式发布的网站
  7. WebSite webSite1 = factory.getWebSiteCategory("新闻");
  8. webSite1.use(new User("tom"));
  9. // 客户要一个以博客形式发布的网站
  10. WebSite webSite2 = factory.getWebSiteCategory("博客");
  11. webSite2.use(new User("jack"));
  12. // 客户要一个以博客形式发布的网站
  13. WebSite webSite3 = factory.getWebSiteCategory("博客");
  14. webSite3.use(new User("smith"));
  15. // 客户要一个以博客形式发布的网站
  16. WebSite webSite4 = factory.getWebSiteCategory("博客");
  17. webSite4.use(new User("king"));
  18. System.out.println("网站的分类共=" + factory.getWebSiteCount());
  19. }
  20. }