Fly Weight Pattern 锛堜韩鍏冩ā寮忥紝 鍏变韩鍏冩暟鎹級

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Fly Weight Pattern 锛堜韩鍏冩ā寮忥紝 鍏变韩鍏冩暟鎹級相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/end' title='end'>end   鍏变韩   website   cto   ebs   mic   http   web   this   

Question

鎶€鏈浘鐗? src=

Analysis

鎶€鏈浘鐗? src=

Introduction

鎶€鏈浘鐗? src=


鎶€鏈浘鐗? src=


鎶€鏈浘鐗? src=

Example

鎶€鏈浘鐗? src=

// 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 锛堜韩鍏冩ā寮忥紝 鍏变韩鍏冩暟鎹級的主要内容,如果未能解决你的问题,请参考以下文章

鏄撻敊鏄撴贩娣嗙煡璇嗙偣璁茶В绯诲垪锛堜節锛夆€斿缓绔嬪姩鎬佽鍒掓ā鍨嬬殑鍩烘湰姝ラ

设计模式---策略模式Strategy Pattern

涓€鏂囧悆閫?3绉嶈璁℃ā寮?瀹冧笉棣?

输入法直接显示 数字输入键盘