美文网首页
享元模式(Flyweight)

享元模式(Flyweight)

作者: bobcorbett | 来源:发表于2017-08-16 09:55 被阅读0次

    享元模式(Flyweight),运用共享技术有效地支持大量细粒度的对象。
    PS:比如String的对象,利用享元模式概念,两个栈指针指向同一个堆地址。
    享元模式可以避免大量非常相似类的开销。在程序设计中,有时需要生产大量细粒度的类实例来表示数据。如果能发现这些实例除了几个参数之外基本都是相同的,有时就能受大幅度地减少需要实例化的类的数量。如果能把那些参数移到类实例的外面,在方法调用时将它们传递进来,就可以通过共享大幅度地减少单实例的数目。

    主方法

    public class main {
        public static void main(String[] args) {
            WebSiteFactory webSiteFactory = new WebSiteFactory();
    
            WebSite fx = webSiteFactory.getWebSiteCategory("产品展示");
            fx.use(new User("小菜"));
    
            WebSite fy = webSiteFactory.getWebSiteCategory("产品展示");
            fy.use(new User("大鸟"));
    
            WebSite fz = webSiteFactory.getWebSiteCategory("产品展示");
            fz.use(new User("娇娇"));
    
            WebSite fl = webSiteFactory.getWebSiteCategory("博客");
            fl.use(new User("老顽童"));
    
            WebSite fm = webSiteFactory.getWebSiteCategory("博客");
            fm.use(new User("桃谷六仙"));
    
            WebSite fn = webSiteFactory.getWebSiteCategory("博客");
            fn.use(new User("南海鳄神"));
    
            System.out.println(String.format("得到网站分类总数为:{%d}", webSiteFactory.countWebSite()));
        }
    }
    

    用户类

    public class User {
        public User(String name) {
            this.name = name;
        }
    
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    

    享元抽象类

    /**
     * 网站抽象类
     */
    public abstract class WebSite {
        public abstract void use(User user);
    }
    

    享元实现类

    /**
     * 具体网站类
     */
    public class WebSiteImpl extends WebSite {
        private String name = "";
    
        public WebSiteImpl(String name) {
            this.name = name;
        }
    
        public void use(User user) {
            System.out.println("网站分类:" + name + " 用户:" + user.getName());
        }
    }
    

    享元工厂类

    import java.util.concurrent.ConcurrentHashMap;
    public class WebSiteFactory {
        private ConcurrentHashMap<String, WebSiteImpl> flyweights = new ConcurrentHashMap<String, WebSiteImpl>();
    
        public WebSite getWebSiteCategory(String key) {
            if (!flyweights.contains(key)) {
                flyweights.put(key, new WebSiteImpl(key));
            }
            return flyweights.get(key);
        }
    
        public int countWebSite() {
            return flyweights.size();
        }
    }
    

    相关文章

      网友评论

          本文标题:享元模式(Flyweight)

          本文链接:https://www.haomeiwen.com/subject/zuobrxtx.html