简要说明

【设计模式-08】Flyweight享元模式-LMLPHP

结合组合模式(Composite)

【设计模式-08】Flyweight享元模式-LMLPHP

一、代码实现

1、Java String中的享元模式

/**
 * @description: Java String 中的享元模式
 * @author: flygo
 * @time: 2022/7/21 11:32
 */
public class TestString {

  public static void main(String[] args) {
    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
    System.out.println(s3.intern() == s4.intern()); // true
  }
}

2、对象池模拟Flyweight享元模式

【设计模式-08】Flyweight享元模式-LMLPHP

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @description: 对象池模拟Flyweight享元模式
 * @author: flygo
 * @time: 2022/7/21 11:37
 */
public class BulletPool {

  List<Bullet> bulletList = new ArrayList<>();

  {
    for (int i = 0; i < 5; i++) {
      bulletList.add(new Bullet());
    }
  }

  public Bullet getBullet() {
    for (int i = 0; i < bulletList.size(); i++) {
      Bullet b = bulletList.get(i);
      if (!b.living) {
        return b;
      }
    }
    return new Bullet();
  }

  public static void main(String[] args) {
    BulletPool bp = new BulletPool();

    for (int i = 0; i < 10; i++) {
      Bullet bullet = bp.getBullet();
      System.out.println(bullet);
    }
  }
}

class Bullet {
  public UUID id = UUID.randomUUID();
  boolean living = true;

  @Override
  public String toString() {
    return "Bullet{" + "id=" + id + '}';
  }
}

二、源码地址

https://github.com/jxaufang168/Design-Patterns【设计模式-08】Flyweight享元模式-LMLPHPhttps://github.com/jxaufang168/Design-Patterns

01-21 06:44