关于Java 设计模式 享元模式 Flyweight

关于Java 设计模式 享元模式 Flyweight

1、IShape.java

package com.ssm.cts.pattern.flyweight;

public interface IShape {
  void draw();
}

2、Circle.java

package com.ssm.cts.pattern.flyweight;

public class Circle implements IShape {
  private String color;

  public Circle(String color) {
    this.color = color;
  }

  @Override
  public void draw() {
    System.out.println("显示" + color + "圆圈");
  }
}

3、ShapeFactory.java

package com.ssm.cts.pattern.flyweight;

import java.util.HashMap;

public class ShapeFactory {
  private static final HashMap<String, IShape> circleMap = new HashMap<>();

  public static IShape getCircle(String color) {
    Circle circle = (Circle) circleMap.get(color);

    if (circle == null) {
      circle = new Circle(color);
      circleMap.put(color, circle);
      System.out.println("创建" + color + "圆圈");
    }
    return circle;
  }
}

4、Demo.java

package com.ssm.cts.pattern.flyweight;

public class Demo {

  private static final String colors[] = { "Red", "Green", "Blue", "White", "Black" };

  public static void main(String[] args) {

    for (int i = 0; i < 10; ++i) {
      Circle circle = (Circle) ShapeFactory.getCircle(getRandomColor());
      circle.draw();
    }
  }

  private static String getRandomColor() {
    return colors[(int) (Math.random() * colors.length)];
  }

}

 

发表回复

您的电子邮箱地址不会被公开。