享元模式

享元模式

定義
  1. 提供了減小對象數量二改善應用所需的對象結構的方法
  2. 運用共享技術有效的支持大量粗粒度的對象。
用通俗的大白話來講就是減小對象的數量,提升對象的利用率,減小內存的使用,提升系統性能。
類型

建立型java

適用場景
  1. 經常應用於系統底層的開發,一遍解決系統的性能問題。
  2. 系統中有大量的類似對象、須要使用緩衝池的場景。
優勢
  1. 減小對象的建立,下降內存中對象的數量,下降系統的內存,提升效率。
  2. 減小內存以外的其餘資源佔用。(對象的建立是消耗其餘的資源的)
缺點
  1. 關注內部/外部狀態、關注線程安全問題。
  2. 系統邏輯的複雜化。(好比咱們常常作一道面試題Integer a=128;Integer b=128;a==b是true仍是false,這裏就有緩存的問題,後面咱們再分析這個)
內部狀態

在享對象類的內部,不會隨着環境改變而改變的狀態。面試

外部狀態

記錄在享元對象的外部,隨着環境改變而改變。不能夠共享的狀態。緩存

內部狀態是享元對象的屬性,不會隨環境變化而變化的屬性。外部狀態咱們打個比方就是在外部調用享元對象的方法時傳過來一個int 這個int 爲1時一種狀態,爲2時一種狀態這就是外部狀態。

咱們來看看怎麼實現。國際慣例假設一個應用場景,假設咱們要作一個部門會議。安全

public interface Employee {
    void report();
}

員工接口有個作報告方法。dom

public class Manager implements Employee {
    @Override
    public void report() {
        System.out.println(reportContent);
    }
    private String title = "部門經理";
    private String department;
    private String reportContent;

    public void setReportContent(String reportContent) {
        this.reportContent = reportContent;
    }

    public Manager(String department) {
        this.department = department;
    }


}

經理實現了員工接口。有三個屬性,標題,部門,報告內容。ide

public class EmployeeFactory {
    private static final Map<String,Employee> EMPLOYEE_MAP = new HashMap<String,Employee>();

    public static Employee getManager(String department){
        Manager manager = (Manager) EMPLOYEE_MAP.get(department);

        if(manager == null){
            manager = new Manager(department);
            System.out.print("建立部門經理:"+department);
            String reportContent = department+"部門彙報:這次報告的主要內容是......";
            manager.setReportContent(reportContent);
            System.out.println(" 建立報告:"+reportContent);
            EMPLOYEE_MAP.put(department,manager);

        }
        return manager;
    }

}

員工工廠,這裏使用了容器單例模式。性能

public class FlyweightTest {
    private static final String departments[] = {"RD","QA","PM","BD"};

    public static void main(String[] args) {
        for(int i=0; i<10; i++){
            String department = departments[(int)(Math.random() * departments.length)];
            Manager manager = (Manager) EmployeeFactory.getManager(department);
            manager.report();
        }
    }
}

這裏咱們定義了一個部門列表,而後隨機的使用其中一個部門去去執行報告操做。this

建立部門經理:RD 建立報告:RD部門彙報:這次報告的主要內容是......
RD部門彙報:這次報告的主要內容是......
建立部門經理:PM 建立報告:PM部門彙報:這次報告的主要內容是......
PM部門彙報:這次報告的主要內容是......
RD部門彙報:這次報告的主要內容是......
建立部門經理:QA 建立報告:QA部門彙報:這次報告的主要內容是......
QA部門彙報:這次報告的主要內容是......
建立部門經理:BD 建立報告:BD部門彙報:這次報告的主要內容是......
BD部門彙報:這次報告的主要內容是......
RD部門彙報:這次報告的主要內容是......
RD部門彙報:這次報告的主要內容是......
PM部門彙報:這次報告的主要內容是......
QA部門彙報:這次報告的主要內容是......
BD部門彙報:這次報告的主要內容是......
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息