圖1 享元模式【點擊查看圖片】java
本質是爲了使用相似常量池的這樣一種緩存結構,用來防止大量的對象新建,耗費大量內存和CPU資源,咱們能夠直接使用已有的一些實例化對象,只用修改其中的字段屬性就能夠變身成爲一個咱們所須要的實例化對象! 緩存
後續能夠使用ConcurrenHashMap來進行線程安全規範。安全
package com.cnblogs.mufasa.demo2; public interface People { void say(); } class Person implements People{ private String country; private boolean gender; private int age; private final String[] StrGender={"Male","Female"}; public Person(String country) { this.country=country; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public boolean isGender() { return gender; } public void setGender(boolean gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public void say() { System.out.println("I was "+age+" years old,a "+StrGender[(gender?0:1)]+",came from "+country); } }
這個是享元模式的核心函數:①使用HashMap存儲實例化對象!Spring中的Definition?!!一個套路;②與單例模式相識的,私有化構造函數;③單例模式中的懶漢加載模式;dom
package com.cnblogs.mufasa.demo2; import java.util.HashMap; public class PersonFactory { private static final HashMap<String, People> peopleHashMap = new HashMap<>();//和單例模式有點像 public static People getPerson(String country) { People people = (People) peopleHashMap.get(country); if(people==null){ people=new Person(country); peopleHashMap.put(country,people); System.out.println("Creating person of country : " + country); } return people; } }
享元模式的核心功能基本上都在工廠類中實現了!ide
package com.cnblogs.mufasa.demo2; public class FlyweightPatternDemo { private static final String[] COUNTRY={ "China", "Russia", "America", "England", "France" }; public static void main(String[] args) { for(int i=0; i < 20; ++i) { Person pr =(Person) PersonFactory.getPerson(getCountry()); pr.setAge(getAge()); pr.setGender(getGender()); pr.say(); } } private static String getCountry() {//獲取國家信息 return COUNTRY[(int)(Math.random()*COUNTRY.length)]; } private static boolean getGender() { return ((int)(Math.random()*2 )==0? true : false); } private static int getAge() { return (int)(Math.random()*100); } }