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

Fly Weight Pattern (享元模式, 共享元数据)

时间:2020-06-27 20:01:58      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:end   共享   website   cto   ebs   mic   http   web   this   

Question

技术图片

Analysis

技术图片

Introduction

技术图片


技术图片


技术图片

Example

技术图片

// Website.java

public abstract class Website {
    public abstract void use();
}
//ConcreteWebsite.java
public class ConcreteWebsite extends Website {
    private String type = ""; // the release type of a website

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

    @Override
    public void use() {
        System.out.println("The release type of a website is :" + type);
    }
}

// WebsiteFactory.java

import java.util.HashMap;

public class WebsiteFactory {
    private HashMap<String, ConcreteWebsite> pool = new HashMap<String, ConcreteWebsite>();

    //根据网站的类型,返回一个网站, 如果没有,则创造一个网站并放入池中
    public Website getWebsiteCategory(String type){
        if(!pool.containsKey(type)){
            pool.put(type, new ConcreteWebsite(type));
        }
        return (Website) pool.get(type);
    }

    //get the number of category
    public int getWebSiteCount(){
        return pool.size();
    }
}
// Client.java
public class Client {
    public static void main(String[] args) {
        WebsiteFactory websiteFactory = new WebsiteFactory();
        Website news = websiteFactory.getWebsiteCategory("news");
        Website wechat = websiteFactory.getWebsiteCategory("wechat");
        Website qq = websiteFactory.getWebsiteCategory("QQ");
        news.use();
        wechat.use();
        qq.use();
        Website news2 = websiteFactory.getWebsiteCategory("news");
        news2.use();
        System.out.println(websiteFactory.getWebSiteCount());
    }
}
//
//        The release type of a website is :wechat
//        The release type of a website is :QQ
//        The release type of a website is :news
//        3

Fly Weight Pattern (享元模式, 共享元数据)

标签:end   共享   website   cto   ebs   mic   http   web   this   

原文地址:https://www.cnblogs.com/nedrain/p/13199523.html

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