重复利用对象,共享元对象
package org.example.ms.flyweight;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* @author Gavin.luo
* @title: flyA
* @projectName MyData
* @description:
* @date 2022/3/16 10:16
*/
public class FlyA {
List<FlyB> flyBList = new ArrayList<>();
{
for (int i = 0; i < 5; i++) {
flyBList.add(new FlyB());
}
}
public FlyB getFlyB() {
for (FlyB fb : flyBList) {
if (!fb.isLiving) {
return fb;
}
}
return new FlyB();
}
}
class FlyB {
public UUID id = UUID.randomUUID();
boolean isLiving = false;
@Override
public String toString() {
return "flyB{" +
"id=" + id +
'}';
}
}
package org.example.ms.flyweight;
/**
* @author Gavin.luo
* @title: Flyweight
* @projectName MyData
* @description: 享元模式测试
* @date 2022/3/16 10:15
*/
public class FlyweightTtest {
public static void main(String[] args) {
FlyA flyA = new FlyA();
for (int i = 0; i < 10; i++) {
FlyB ff = flyA.getFlyB();
if (i % 2 == 0) {
ff.isLiving = true;
}
System.out.println(ff);
}
}
}