享元模式git
public interface IFlyweight { void print(); }
public class Flyweight implements IFlyweight { private String id; public Flyweight(String id){ this.id = id; } @Override public void print() { System.out.println("Flyweight.id = " + getId() + " ..."); } public String getId() { return id; } }
public class FlyweightFactory { private Map<String, IFlyweight> flyweightMap = new HashMap(); public IFlyweight getFlyweight(String str){ IFlyweight flyweight = flyweightMap.get(str); if(flyweight == null){ flyweight = new Flyweight(str); flyweightMap.put(str, flyweight); } return flyweight; } public int getFlyweightMapSize(){ return flyweightMap.size(); } }
public static void main(String[] args) { FlyweightFactory flyweightFactory = new FlyweightFactory(); IFlyweight flyweight1 = flyweightFactory.getFlyweight("A"); IFlyweight flyweight2 = flyweightFactory.getFlyweight("B"); IFlyweight flyweight3 = flyweightFactory.getFlyweight("A"); flyweight1.print(); flyweight2.print(); flyweight3.print(); System.out.println(flyweightFactory.getFlyweightMapSize()); }
Flyweight.id = A ... Flyweight.id = B ... Flyweight.id = A ... 2
https://github.com/Seasons20/DisignPattern.git
ENDgithub