1. 运用共享技术有效地支持大量细粒度的对象。简单来说,享元模式可以通过共享的方式避免创建出大量的对象,减少程序的内存损耗。
2. 内部状态与外部状态: 在享元对象内部并且不会随环境改变而改变的共享部分,可以称为是享元对象的内部状态,而随环境改变而改变的、不可以共享的状态就是外部状态。
3. 享元模式的通用示例:
/**
* @author beck.yang
* @date 2022/7/5 19:14
* @description 抽象享元类
*/
public abstract class FlyWeight {
// 内部状态
private String innerProperty;
// 外部状态
private final String outerProperty;
public FlyWeight(String outerProperty){
this.outerProperty = outerProperty;
}
public abstract void operation();
public String getInnerProperty() {
return innerProperty;
}
public void setInnerProperty(String innerProperty) {
this.innerProperty = innerProperty;
}
}
/**
* @author beck.yang
* @date 2022/7/5 19:17
* @description 具体享元类
*/
public class ConcreteFlyWeight extends FlyWeight{
public ConcreteFlyWeight(String outerProperty) {
super(outerProperty);
}
@Override
public void operation() {
System.out.println("ConcreteFlyWeight operation...");
}
}
/**
* @author beck.yang
* @date 2022/7/5 19:17
* @description 具体享元类(不支持共享)
*/
public class UnSharedConcreteFlyWeight extends FlyWeight{
public UnSharedConcreteFlyWeight(String outerProperty) {
super(outerProperty);
}
@Override
public void operation() {
System.out.println("ConcreteFlyWeight operation...");
}
}
/**
* @author beck.yang
* @date 2022/7/5 19:20
* @description 享元工厂
*/
public class FlyWeightFactory {
private Map<String, FlyWeight> flyWeightMap = new HashMap<>();
public FlyWeight getFlyWeight(String key){
if (flyWeightMap.containsKey(key)) {
return flyWeightMap.get(key);
}else {
ConcreteFlyWeight concreteFlyWeight = new ConcreteFlyWeight(key);
flyWeightMap.put(key,concreteFlyWeight);
return concreteFlyWeight;
}
}
public int size(){
return flyWeightMap.size();
}
}
/**
* @author beck.yang
* @date 2022/7/5 19:24
* @description 享元模式
*/
public class Main {
public static void main(String[] args) {
FlyWeightFactory factory = new FlyWeightFactory();
factory.getFlyWeight("A");
factory.getFlyWeight("A");
factory.getFlyWeight("B");
factory.getFlyWeight("B");
System.out.println(factory.size());
}
}