设计模式-享元模式

设计模式-享元模式

享元模式(Flyweight Pattern)是一种结构型设计模式,主要用于减少创建大量相似对象对内存资源的消耗,通过共享这些对象来提高程序性能和系统资源利用率。在实际应用场景中string就是使用了享元模式,string a = “123”; string b = “123”;

我们假设有一个场景是需要创建大量的颜色对象,但其实大部分颜色对象的RGB值是重复的,因此可以通过享元模式来共享这些重复的颜色对象,以节省内存空间。

代码示例

/**
 * 颜色接口
 */
public interface Color {
    void paint(ColorContext context);

    // 获取颜色的RGB值
    int getRGB();
}
/**
 * 具体颜色实现
 */
public class ConcreteColor implements Color{
    private final int rgb;

    public ConcreteColor(int rgb) {
        this.rgb = rgb;
    }

    @Override
    public void paint(ColorContext context) {
        System.out.println("RGB的值是: " + rgb);
        // 在实际场景中会使用rgb值来填充颜色等操作
    }

    @Override
    public int getRGB() {
        return rgb;
    }
}
/**
 * 颜色上下文,存储享元对象外部状态
 */
public class ColorContext {
    private Point position;

    public ColorContext(Point position) {
        this.position = position;
    }

    public Point getPosition() {
        return position;
    }
}
/**
 * 享元颜色工厂
 */
public class ColorFactory {
    private Map<Integer, Color> colorMap = new HashMap<>();

    public Color getColor(int rgb) {
        if (!colorMap.containsKey(rgb)) {
            colorMap.put(rgb, new ConcreteColor(rgb));
        }
        return colorMap.get(rgb);
    }
}
/**
 * 享元模式客户端
 */
public class FlyweightDemo {
    public static void main(String[] args) {
        ColorFactory factory = new ColorFactory();

        Point pos1 = new Point(0, 0);
        Point pos2 = new Point(10, 10);

        Color red1 = factory.getColor(001);
        red1.paint(new ColorContext(pos1));

        // 同样的RGB值,复用同一个对象
        Color red2 = factory.getColor(001);
        red2.paint(new ColorContext(pos2));
        
        if (red1 == red2){
            System.out.println("对象示例相同");
        }

    }
}

打印结果:

Connected to the target VM, address: '127.0.0.1:49072', transport: 'socket'
RGB的值是: 1
RGB的值是: 1
对象示例相同
Disconnected from the target VM, address: '127.0.0.1:49072', transport: 'socket'

你可能感兴趣的:(设计模式,享元模式)