本文主要是介绍设计模式-结构型-享元模式Flyweight,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
享元模式的特点:
享元模式可以共享相同的对象,避免创建过多的对象实例,从而节省内存资源
使用场景:
常用于需要创建大量相似的对象的情况
享元接口类
public interface Flyweight { void operate(String extrinsicState); }
享元实现类
public class ConcreteFlyweight implements Flyweight {@Overridepublic void operate(String extrinsicState) {System.out.println("固有状态: " + intrinsicState);System.out.println("外部状态 " + extrinsicState);}
}
享元工厂类
public class FlyweightFactory {private Map<String, Flyweight> flyweights;public Flyweight getFlyweight(String intrinsicState) {if (flyweights.containsKey(intrinsicState)) {return flyweights.get(intrinsicState);} else {Flyweight flyweight = new ConcreteFlyweight(intrinsicState);flyweights.put(intrinsicState, flyweight);return flyweight;}}
}
演示类
public class Demo {public static void main(String[] args) {FlyweightFactory factory = new FlyweightFactory();//保存固有状态Flyweight flyweight1 = factory.getFlyweight("SharedState");Flyweight flyweight2 = factory.getFlyweight("SharedState");//处理外部状态flyweight1.operate("ExtrinsicState1");flyweight2.operate("ExtrinsicState2");}
}
演示结果
为了使演示代码更简洁,我移除了构造方法和set/get方法
这篇关于设计模式-结构型-享元模式Flyweight的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!