利用共享的形式来实现对象复用,这样能够大幅度缩小对象创立的数量、防止了创立大量类似对象的开销,从而进步了资源的利用率。
在之前的单例模式中,已经写过一个“多例模式”的 demo,一个类能够有固定个数的对象实例,每次须要应用这个类的实例的时候就从存有对象实例的汇合中取一个应用。
public class MultiSingleton {private static Map<Integer,MultiSingleton> 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<String,Flyweight> 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