|
享元模式主要解決減少創(chuàng)建對象數(shù)量,減少內(nèi)存占用,節(jié)約資源,提高性能。 享元模式先從已有對象中匹配,如果有則使用已有對象,沒有才會創(chuàng)建新的對象, 這樣可以實(shí)現(xiàn)對象的復(fù)用,減少不必要的創(chuàng)建。 基本思路:使用HashMap將對象存儲起來,后續(xù)使用時(shí)在HashMap中尋找,如果有則使用已有對象, 如果沒有則創(chuàng)建對象,并將其放在HashMap中。 假設(shè)現(xiàn)在需要繪制圓形,圓形有幾個(gè)參數(shù),圓心位置,半徑,顏色。 如果每次繪制圓,圓心,半徑每次都可能不一樣。 但是,不同位置,不同半徑的圓的顏色可能是相同的。 此時(shí)我們就可以通過顏色來區(qū)分圓。 例如一個(gè)圓半徑為3,一個(gè)圓半徑為10,但都是紅色的圓, 我們就只需要創(chuàng)建一個(gè)紅色圓對象,為其設(shè)置半徑和位置即可,不必創(chuàng)建兩個(gè)對象。 Shape public interface Shape {
void draw();
}Circle, 實(shí)現(xiàn)Shape接口,主要屬性,x,y圓心坐標(biāo),radius半徑,color顏色。 初始化對象時(shí),構(gòu)造函數(shù)設(shè)Color public class Circle implements Shape{
private String color;
private int x;
private int y;
private int radius;
public String getColor() {
return color;
}
public Circle(String color) {
super();
this.color = color;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
@Override
public void draw() {
// TODO Auto-generated method stub
System.out.println("Circle: Draw() [Color : " color
", x : " x ", y :" y ", radius :" radius "]");
}
}ShapeFactory import java.util.HashMap;
import java.util.Map;
public class ShapeFactory {
private static Map<String,Shape> hMap = new HashMap<String,Shape>();
public static Circle getCircle(String color) {
Circle circle = (Circle)hMap.get(color);//首先通過顏色獲取已存在的圓
if(circle == null) { //如果沒有則為其創(chuàng)建,并將其放入hMap中
circle = new Circle(color);
hMap.put(color, circle);//每次創(chuàng)建對象則輸出創(chuàng)建信息
System.out.println("----create circle:" color "----");
}
return circle;
}
}Main public class Main {
private static String[] colors = {"red","green","bule"};
public static void main(String[] args) {
for(int i = 0; i < 10; i ) {
//從工廠中獲取圓對象,
//如果有則直接獲取并返回
//如果沒有則創(chuàng)建對象,并將其放入HashMap中,并返回創(chuàng)建對象
Circle circle = ShapeFactory.getCircle(getRandomColor());
circle.setX(getRandom());//隨機(jī)指定圓心位置
circle.setY(getRandom());
circle.setRadius(getRandom());//隨機(jī)指定半徑
circle.draw();
}
}
//生成隨機(jī)顏色
public static String getRandomColor() {
return colors[((int)(Math.random() * 10)) % colors.length];
}
//生成隨機(jī)數(shù)
public static int getRandom() {
return (int)(Math.random() * 100);
}
}運(yùn)行結(jié)果: 觀察運(yùn)行結(jié)果可以看到,繪制的圓有10個(gè),但是只創(chuàng)建了3個(gè)對象。 這樣可以大大減少對象數(shù)量。 參考資料: https://www.runoob.com/design-pattern/flyweight-pattern.html 來源:http://www./content-4-222001.html |
|
|