用通俗的大白話來講就是減小對象的數量,提升對象的利用率,減小內存的使用,提升系統性能。
建立型java
在享對象類的內部,不會隨着環境改變而改變的狀態。面試
記錄在享元對象的外部,隨着環境改變而改變。不能夠共享的狀態。緩存
內部狀態是享元對象的屬性,不會隨環境變化而變化的屬性。外部狀態咱們打個比方就是在外部調用享元對象的方法時傳過來一個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部門彙報:這次報告的主要內容是......