diff --git a/src/main/java/com/msb/flyweight/Main.java b/src/main/java/com/msb/flyweight/Main.java new file mode 100644 index 0000000..7bcd22f --- /dev/null +++ b/src/main/java/com/msb/flyweight/Main.java @@ -0,0 +1,66 @@ +package com.msb.flyweight;/** + * @Author bingor + * @Date 2022/10/14 19:40 + * @Description: com.msb.flyweight + * @Version: 1.0 + */ + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +/** + *@ClassName Main + *@Description TODO + *@Author bingor + *@Date 2022/10/14 19:40 + *@Version 3.0 + */ +public class Main { + + public static void main(String[] args) { + + BulletPool pool = new BulletPool(); + + for (int i=0; i<10 ; i++) { + Bullet bullet = pool.getBullet(); + System.out.println(bullet); + } + } + +} + +class Bullet { + private UUID id = UUID.randomUUID(); + private boolean live = false; + + @Override + public String toString() { + return "Bullet{" + + "id=" + id + + '}'; + } + + public boolean isLive() { + return live; + } +} + +class BulletPool { + + private List bullets = new ArrayList<>(); + + { + for (int i=0; i<5; i++) { + bullets.add(new Bullet()); + } + } + + public Bullet getBullet() { + for (Bullet bullet : bullets) { + if( ! bullet.isLive()) return bullet; + } + return new Bullet(); + } + +} diff --git a/src/test/java/CommonTest.java b/src/test/java/CommonTest.java index db1a091..6dbeb59 100644 --- a/src/test/java/CommonTest.java +++ b/src/test/java/CommonTest.java @@ -48,4 +48,18 @@ public class CommonTest { return true; } + @Test + public void testString() { + String s1 = "abc"; + String s2 = "abc"; + String s3 = new String("abc"); + String s4 = new String("abc"); + + System.out.println(s1 == s2); //true, 因为都是从字符串常量池取出的,指向的是同一个对象 + System.out.println(s1 == s3); //false 因为两个对象地址不一样 + System.out.println(s3 == s4); //false 因为两个对象地址不一样 + System.out.println(s3.intern() == s1); //true s3.intern() 指的是该地址指向内部指向常量池的对象 + System.out.println(s3.intern() == s4.intern()); //true + } + }