坦克大战(一期)-设计模式-享元模式

DesignPatterns
bingor 2 years ago
parent 9e1e86d93a
commit 411050d429

@ -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<Bullet> 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();
}
}

@ -48,4 +48,18 @@ public class CommonTest {
return true; 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
}
} }

Loading…
Cancel
Save