利用共享的方式来实现对象复用,这样可以大幅度减少对象创建的数量、避免了创建大量相似对象的开销,从而提高了资源的利用率。
在之前的单例模式中,曾经写过一个“多例模式”的demo,一个类可以有固定个数的对象实例,每次需要使用这个类的实例的时候就从存有对象实例的集合中取一个使用。
public class MultiSingleton {
private static Map multiSingletonMap = new HashMap<>();
static {
multiSingletonMap.put(0,new MultiSingleton());
multiSingletonMap.put(1,new MultiSingleton());
multiSingletonMap.put(2,new MultiSingleton());
}
private MultiSingleton(){
}
public static MultiSingleton getInstance() {
return multiSingletonMap.get(new Random().nextInt(3));
}
}
享元模式中有以下角色
- 享元类:定义了享元对象需要实现的公共操作方法。在该方法中会使用一个状态作为输入参数,也叫做外部状态。
- 享元工厂类:管理一个享元对象类的缓存池,它会存储享元对象之间需要传递的共有状态。
- 具体享元类:享元类的实现类。
实现
public interface Flyweight {
void operation();
}
public class ConcreteFlyweightA implements Flyweight{
@Override
public void operation() {
System.out.println(\"ClassName:\"+this.getClass().getSimpleName());
}
}
public class ConcreteFlyweightB implements Flyweight{
@Override
public void operation() {
System.out.println(\"ClassName:\"+this.getClass().getSimpleName());
}
}
public class FlyweightFactory {
private Map map = new HashMap();
public FlyweightFactory() {
map.put(\"A\",new ConcreteFlyweightA());
map.put(\"B\",new ConcreteFlyweightB());
}
public Flyweight getFlyweight(String p){
return map.get(p);
}
}
测试
public class FlyweightTest {
@Test
public void test(){
FlyweightFactory factory = new FlyweightFactory();
Flyweight flyweightA = factory.getFlyweight(\"A\");
Flyweight flyweightB = factory.getFlyweight(\"B\");
flyweightA.operation();
flyweightB.operation();
}
}
======结果=======
ClassName:ConcreteFlyweightA
ClassName:ConcreteFlyweightB