Object reuse is realized by the sharing method, which can greatly reduce the number of objects created, avoid the overhead of creating a large number of similar objects, and improve the utilization of resources.
In the previous singleton mode, a demo of "multiple instance mode" has been written. A class can have a fixed number of object instances. Every time an instance of this class needs to be used, it is extracted from the collection of object instances. Take one to use.
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));
}
}
Flyweight has the following roles
- Flyweight class: defines the public operation methods that flyweight objects need to implement. In this method, a state is used as an input parameter, also called an external state.
- Flyweight factory class: manages a cache pool of flyweight object classes, which stores the shared state that needs to be passed between flyweight objects.
- Concrete flyweight class: the implementation class of the flyweight class.
accomplish
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);
}
}
test
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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。