定义:面向对象技术可以很好地解决一些灵活性或可扩展性问题,但在很多情况下需要在系统中增加类和对象的个数。当对象数量太多时,将导致运行代价过高,带来性能下降等问题。
优点:1.减少了对象的创立,减少了内存的使用
缺点:1.提高了系统的复杂度。
2.需要分离出内部状态和外部状态,而外部状态具有固化特性,不应该随着内部状态的改变而改变
使用场景:1.String常量池、数据库连接池、缓冲池等等都是享元模式
原理:1缓存对象,统一管理,不必挨个创建,用 HashMap 存储这些对象。(建立对象池),
类图:
实例代码:
抽象享元角色
1. 2. interface IFlyweight { 3. void operation(String extrinsicState); 4. }
具体享元角色
1. static class ConcreteFlyweight implements IFlyweight { 2. private String intrinsicState; 3. 4. public ConcreteFlyweight(String intrinsicState) { 5. this.intrinsicState = intrinsicState; 6. } 7. 8. @Override 9. public void operation(String extrinsicState) { 10. //方法。。。。 11. } 12. }
享元工厂
1. 2. static class FlyweightFactory { 3. private static Map<String, IFlyweight> pool = new HashMap<>(); 4. 5. // 因为内部状态具备不变性,因此作为缓存的键 6. public static IFlyweight getFlyweight(String intrinsicState) { 7. if (!pool.containsKey(intrinsicState)) { 8. IFlyweight flyweight = new ConcreteFlyweight(intrinsicState); 9. pool.put(intrinsicState, flyweight); 10. } 11. return pool.get(intrinsicState); 12. } 13. }
调用
1. class Client { 2. public static void main(String[] args) { 3. IFlyweight flyweight1 = FlyweightFactory.getFlyweight("aa"); 4. IFlyweight flyweight2 = FlyweightFactory.getFlyweight("bb"); 5. flyweight1.operation("a"); 6. flyweight2.operation("b"); 7. }
栗子
抽象享元角色
1. //选肥皂 2. interface IChooseSoap{ 3. 4. void toChoose(String soapColor); 5. }
具体享元角色
1. 2. 3. public class ChooseSoap extends IChooseSoap{ 4. 5. private String name = ""; 6. 7. public ChooseSoap (String color) { 8. this.name = name; 9. } 10. 11. @Override 12. public void toChoose() { 13. System.out.println("肥皂颜色是:" + color); 14. } 15. 16. }
工厂类(处理内部对象)
1. public class Factory { 2. 3. private HashMap<String, IChooseSoap> pool = new HashMap<>(); 4. 5. //获得肥皂 6. public IChooseSoap chooseSoap(String color) { 7. //如果没有这个颜色的 就买一个放在池中 8. if(!pool.containsKey(color)) { 9. pool.put(color, new ChooseSoap(keycolor); 10. } 11. //如果池中有 那么就在池中取 12. return (IChooseSoap)pool.get(color); 13. } 14. 15. 16. }
调用
1. public class Client { 2. 3. public static void main(String[] args) { 4. Factory Factory = new Factory(); 5. Factory.chooseSoap('粉色'); 6. } 7. 8. }