From 411050d429c3f257bc4a4a56be8ac33d6f8619e9 Mon Sep 17 00:00:00 2001 From: bingor Date: Fri, 14 Oct 2022 20:02:49 +0800 Subject: [PATCH] =?UTF-8?q?=E5=9D=A6=E5=85=8B=E5=A4=A7=E6=88=98=EF=BC=88?= =?UTF-8?q?=E4=B8=80=E6=9C=9F=EF=BC=89-=E8=AE=BE=E8=AE=A1=E6=A8=A1?= =?UTF-8?q?=E5=BC=8F-=E4=BA=AB=E5=85=83=E6=A8=A1=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/msb/flyweight/Main.java | 66 +++++++++++++++++++++++ src/test/java/CommonTest.java | 14 +++++ 2 files changed, 80 insertions(+) create mode 100644 src/main/java/com/msb/flyweight/Main.java 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 + } + }