Flyweight

import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;

public class FooBar
{
  public static void main(String args[]) {
    LetterFactory factory = new LetterFactory();
    List<Letter> letters = new ArrayList<Letter>();
    letters.add(factory.getLetter('s'));
    letters.add(factory.getLetter('s'));
    letters.add(factory.getLetter('a'));
    letters.add(factory.getLetter('a'));
    letters.add(factory.getLetter('i'));
    letters.add(factory.getLetter('i'));
    letters.add(factory.getLetter('k'));
    letters.add(factory.getLetter('k'));
    letters.add(factory.getLetter('a'));
    letters.add(factory.getLetter('a'));
    letters.forEach(Letter::print);
    System.out.print("\nLetterFactory's PoolSize => " + factory.getPoolSize() + "\n");
  }
}

class Letter
{
  private char c;
  public Letter(char c) {
    this.c = c;
  }
  public void print() {
    System.out.print(c);
  }
}

class LetterFactory
{
  private Map<Character, Letter> pool;
  public LetterFactory() {
    pool = new HashMap<Character, Letter>();
  }
  public Letter getLetter(char c) {
    Letter letter = pool.get(c);
    if(letter == null) {
      letter = new Letter(c);
      pool.put(c, letter);
    }
    return letter;
  }
  public int getPoolSize() {
    return pool.size();
  }
}
  実行結果 f:id:blau_coerulea:20160822204044p:plain

Remove all ads