简介:使用共享物件,用来尽可能减少内存使用量以及分享资讯给尽可能多的相似物件
目的:
总结:通过共享模式减少内存使用和重复对象
组成:享元管理器, 享元, 辅助类
1,享元
package com.design.r.flyweight; /** * 英雄基类 */ public abstract class Hero { protected String userName; //英雄名称 protected String[] kills = new String[4];//技能 public Hero() { super(); this.userName = getUserName(); initKills(); } public void attact(){ System.out.println(userName + " 发动了物理攻击!"); } public abstract String getUserName(); public abstract void initKills(); }
package com.design.r.flyweight; /** * 英雄A */ public class HeroA extends Hero { @Override public String getUserName() { return "英雄A"; } @Override public void initKills() { kills[0] = "技能A-1"; kills[1] = "技能A-2"; kills[2] = "技能A-3"; kills[3] = "技能A-4"; } }
package com.design.r.flyweight; /** * 英雄B */ public class HeroB extends Hero { @Override public String getUserName() { return "英雄B"; } @Override public void initKills() { kills[0] = "技能B-1"; kills[1] = "技能B-2"; kills[2] = "技能B-3"; kills[3] = "技能B-4"; } }
2,辅助类
package com.design.r.flyweight; /** * 英雄状态和技能的组合 */ public class Role { private Hero hero;//英雄 private Long bp; //血量 private Long mp; //蓝量 public Role(Hero hero) { super(); this.hero = hero; } public void attact(){ hero.attact(); } public Long getBp() { return bp; } public void setBp(Long bp) { this.bp = bp; } public Long getMp() { return mp; } public void setMp(Long mp) { this.mp = mp; } }
3,享元管理器
package com.design.r.flyweight; import java.util.HashMap; import java.util.Map; /** * 对英雄单例管理, 达到共享功能 */ public class HeroManager { private static HeroManager heroManager = new HeroManager(); private Map<String, Hero> heroMap = new HashMap<>(); public static HeroManager getInstance(){ return heroManager; } public Hero getHero(String userName){ Hero hero = heroMap.get(userName); if(hero == null){ if("英雄A".equals(userName)){ hero = new HeroA(); }else if("英雄B".equals(userName)){ hero = new HeroB(); } heroMap.put(userName, hero); return hero; }else{ return hero; } } }
4,Main
package com.design.r.flyweight; /** * 18-享元模式 * * 通过共享模式减少内存使用和重复对象 */ public class MainTest { public static void main(String[] args) { //使用享元模式后,再创建了4个英雄后,HeroA和HeroB都是单例并没有产生4个实例 HeroManager heroManager = new HeroManager(); Role hero1 = new Role(heroManager.getHero("英雄A")); Role hero2 = new Role(heroManager.getHero("英雄A")); Role hero3 = new Role(heroManager.getHero("英雄B")); Role hero4 = new Role(heroManager.getHero("英雄B")); } }