小Q:什么是设计模式
慢慢:设计模式是系统服务设计中针对常见场景的一种解决方案,可以解决功能逻辑开发中遇到的共性问题。设计模式并不局限最终的实现方案,而是在这种概念模式下,解决系统设计中的代码逻辑问题。
小Q:什么是亨元模式
慢慢:亨元模式主要用于减少创建对象的数量,以减少内存占用和提高性能。这种类型的设计模式属于结构型模式,他提供了减少对象数量从而改善应用所需的对象结构。亨元模式尝试重用现有的同类对象,如果未找到匹配的对象,则创建新对象。常见的亨元模式有数据库连接池,线程池等池化技术。
小Q:明白了,赶快上代码吧。
慢慢:好的。
public interface Shape {
void draw();
}
public class Circle implements Shape {
public String color;
public int x;
public int y;
public int radius;
public Circle(String color) {
this.color = color;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setRadius(int radius) {
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Circle: Draw() [Color : " + color + ",x:" + ",y:" + y + ",radius:" + radius);
}
}
创建一个工厂,生成基于给定信息的实体类的对象。
public class ShapeFactory {
private static final HashMap<String, Shape> circleMap = new HashMap<>();
public static Shape getCircle(String color) {
Circle circle = (Circle) circleMap.get(color);
if (circle == null) {
circle = new Circle(color);
circleMap.put(color, circle);
System.out.println("Creating circle of color : " + color);
}
return circle;
}
}
使用该工厂,通过传递颜色信息来获取实体类的对象。
public class FlyweightPatternDemo {
private static final String colors[] = {"Red", "Green", "Blue", "White", "Black"};
public static void main(String[] args) {
for (int i = 0; i < 20; i++) {
Circle circle = (Circle) ShapeFactory.getCircle(getRandomColor());
circle.setX(getRandomX());
circle.setY(getRandomY());
circle.setRadius(100);
circle.draw();
}
}
private static String getRandomColor() {
return colors[(int) (Math.random()*colors.length)];
}
private static int getRandomX() {
return (int) (Math.random() * 100);
}
private static int getRandomY() {
return (int) (Math.random() * 100);
}
}