[Design Pattern] Flywight Pattern 简单案例

Flywight Pattern, 即享元模式,用于减少对象的创建,降低内存的占用,属于结构类的设计模式。根据名字,我也将其会理解为 轻量模式。

下面是享元模式的一个简单案例。

享元模式,主要是重用已有的对象,通过修改部分属性重新使用,避免申请大量内存。

本模式需要主要两个点:

1. 对象的 key 应该是不可变得,本例中 color 作为 key,所以我在 color 前添加了 final 的修饰符。

2. 并非线程安全,多个线程同时获取一个对象,并同时修改其属性,会导致无法预计的结果。

代码实现:

public interface Shape {

    public void draw();
}

Circle 类实现 Shape 接口

public class Circle implements Shape {

    private int x;
    private int y;
    private int radius;
    
    private final String color;
    
    public Circle(String color){
        this.color = color;
    }
    
    @Override
    public void draw() {
        System.out.println(" Circle draw - ["  + color + "] x :" + x + ", y :" + y + ", radius :" + radius);
    }

    public void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }
    
    public void setRadius(int radius) {
        this.radius = radius;
    }
}

ShapeFactory 作为一个工厂,提供 Circle 的对象,同时负责重用 color 相同的对象。

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

    public Shape getCircle(String color){
        
        Shape circle = null;
        if (circleMap.containsKey(color)){
            circle = (Circle)circleMap.get(color);
        }
        else{
            System.out.println(" Createing cicle - " + color);
            circle = new Circle(color);
            circleMap.put(color, circle);
        }
        
        return circle;
    }
}

 代码演示,多次调用工厂 ShapeFactory 获得对象

public class FlyweightPatternDemo {

    static String[] colors = "red,green,blue,black,white".split(",");
    
    public static void main(){
        
        ShapeFactory shapeFactory = new ShapeFactory();
        
        shapeFactory.getCircle("red");
        
        for (int i = 0; i < 20; i++){
            Circle circle = (Circle)shapeFactory.getCircle(getRandomColor());
            circle.setX(getRandomX());
            circle.setY(getRandomY());
            circle.setRadius(getRandomRadius());
            circle.draw();
        }
    }
    
    public static String getRandomColor(){
        return colors[(int)(Math.random() * colors.length)];
    }

    public static int getRandomX(){
        return (int)(Math.random() * 100);
    }
    
    public static int getRandomY(){
        return (int)(Math.random() * 100);
    }
    
    public static int getRandomRadius(){
        return (int)(Math.random() * 100);
    }    
}

参考资料

Design Patterns - Flyweight Pattern, TutorialsPoint

原文地址:https://www.cnblogs.com/TonyYPZhang/p/5515292.html