码迷,mamicode.com
首页 > 其他好文 > 详细

享元模式

时间:2020-02-03 10:01:46      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:client   nta   factory   stat   size   else   count   cto   rac   

一、定义

享元模式(Flyweight),运用共享技术有效的支持大量细粒度的对象。

二、示例代码

/*外部对象*/
public class User {
    private String name;

    public User(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

public abstract class WebSite {
    public abstract void use(User user);
}

public class ConcreteWebsite extends WebSite{
 private String name;

    public ConcreteWebsite(String name) {
        this.name = name;
    }


    @Override
    public void use(User user) {
        System.out.println("网站名:"+name+",用户名:"+user.getName());
    }
}

import java.util.HashMap;

public class WebsiteFactory {
    private HashMap<String, WebSite> hashMap = new HashMap();

    public WebSite getWebSite(String name) {
        if (hashMap.containsKey(name)) {
            return hashMap.get(name);
        } else {
            ConcreteWebsite concreteWebsite = new ConcreteWebsite(name);
            hashMap.put(name, concreteWebsite);
            return new ConcreteWebsite(name);
        }
    }
    public int countWeb(){
        return hashMap.size();
    }
}

public class Client {
    public static void main(String[] args) {
        WebsiteFactory websiteFactory=new WebsiteFactory();
       WebSite webSite  =websiteFactory.getWebSite("首页");
       User user=new User("huni");
       webSite.use(user);
       WebSite webSite2  =websiteFactory.getWebSite("标题");
       User user2=new User("knock");
       webSite2.use(user2);
       WebSite webSite3  =websiteFactory.getWebSite("标题");
       User user3=new User("jack");
       webSite3.use(user3);
        System.out.println("生成的网站对象数量:"+   websiteFactory.countWeb());


    }
}

享元模式

标签:client   nta   factory   stat   size   else   count   cto   rac   

原文地址:https://www.cnblogs.com/yfy-/p/12254390.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!