Skip to main content
 首页 » 编程设计

Java 享元模式

2022年07月19日149fff_TT

1.享元模式

享元模式(Flyweight Pattern)主要用于减少对象的数量,以减少内存占用和提高性能。属于结构型模式,它提供了减少对象数量从而改
善应用所需的对象结构的方式。享元模式尝试重用现有的同类对象,如果未找到匹配的对象,则创建新对象。

特别像工厂模式,工厂模式中是new一个对象返回的,享元模式是共享一个对象。

实现细节:用唯一标识码判断,如果在内存中有,则返回这个唯一标识码所标识的对象。若没有就创建一个对象并将其放入缓存池(HashMap)中。

2.例子Demo

import java.util.HashMap; 
 
interface Shape { 
    public void draw(); 
} 
 
 
class Circle implements Shape { 
    private int x; 
    private int y; 
    private int r; 
    private String color; 
 
    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 setR(int r) { 
        this.r = r; 
    } 
 
    public void draw() { 
        System.out.println("Circle: [ color: " + color + " X: " + x + " Y: " + y + " R: " + r + " ]"); 
    } 
} 
 
 
class ShapeFactory { 
    private HashMap<String, Shape> map = new HashMap<String, Shape>(); 
 
    public Shape getCircle(String color) { 
        Shape circle = map.get(color); 
        if (circle == null) { 
            System.out.println("Create new circle, Color: " + color); 
            circle = new Circle(color); 
            map.put(color, circle); 
        } 
        return circle; 
    }  
} 
 
 
public class FlyweightPatternDemo { 
    private static final String colors[] = { 
        "green", "red", "blue", "dark", "gray", "yellow" 
    }; 
 
    public static void main(String args[]) { 
        ShapeFactory shapeFactory = new ShapeFactory(); 
 
        for (int i = 0; i < 20; i++) { 
            /*强制转换为Circle里后这些方法才可见*/ 
            Circle circle = (Circle)shapeFactory.getCircle(getRandomColor()); 
            circle.setX(getRandomX()); 
            circle.setY(getRandomY()); 
            circle.setR(getRandomR()); 
            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); 
    } 
 
    private static int getRandomR() { 
        return (int)(Math.random() * 100); 
    } 
}

参考:http://www.runoob.com/design-pattern/flyweight-pattern.html


本文参考链接:https://www.cnblogs.com/hellokitty2/p/10717932.html
阅读延展