定義:它使用共享物件,用來盡可能減少內存使用量以及分享資訊給盡可能多的相似物件;它適合用于只是因重復而導致使用無法令人接受的大量內存的大量物件。
特點:大大減少對象的創建,降低系統的內存,使效率提高。
企業級開發及常用框架中的應用:數據庫的連接池,String的常量緩存池
具體代碼實例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
|
import java.util.HashMap; import java.util.Map; import java.util.Random; public class Demo { public static void main(String[] args) { for ( int i = 0 ; i < 10 ; i++){ Circle circle = new Circle(getColor()); circle.setRadius(getRadius()); circle.setX(getZ()); circle.setY(getZ()); circle.draw(); } } public static String getColor(){ String[] colors = { "紅色" , "橙色" , "黃色" , "青色" , "綠色" }; Random random = new Random(); int index = random.nextInt( 4 ); return colors[index]; } public static double getRadius(){ Random random = new Random(); return random.nextDouble()* 20 ; } public static int getZ(){ Random random = new Random(); return random.nextInt( 100 ); } } /** * 抽象享元類 * 這里以畫圖形舉例:比如畫圓,加入顏色固定,畫圓的方式都是一樣的,所不同的就是圓形的位置和圓的半徑 */ interface Shape{ public void draw(); } /** * 具體享元類 * 這里創建具體的享元類,類中包含了可以共享的數據和不可共享的數據 * 例如:可以共享的顏色以及隱形的畫圓方式,不可共享的半徑和坐標 */ class Circle implements Shape{ private int x; private int y; private double radius; private String color; public Circle(String color) { 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 double getRadius() { return radius; } public void setRadius( double radius) { this .radius = radius; } public String getColor() { return color; } public void setColor(String color) { this .color = color; } public void draw() { System.out.println( "畫了一個圓心坐標為:(" + this .x+ "," + this .y+ "),半徑為" + this .radius+ "," + this .color+ "的圓" ); } } /** * 工廠類:享元模式的具體體現其實是在這一塊得到實現的,在這一塊我們可以清楚的了解到共享了哪些屬性或者數據 * 在這里假設圓的顏色是固定的,我們只能畫固定的幾種顏色的圓 * 在這里例子中對應的共享數據就應該是對應的顏色屬性和隱形的不可見的還原的方式,這個在前面交代過,所有圓的 * 畫的方式是一樣的 */ class CircleFactory{ private static Map<String, Circle> map = new HashMap<>(); public static Circle getCircle(String color){ Circle c = map.get(color); if (c == null ){ c = new Circle(color); map.put(color, c); return c; } return c; } } |
享元模式主要為了解決大量類似對象占用大量內存的現象,因為內存是珍貴的資源,所以我們講這些相似對象進行歸類,提取出相同部分用以共享,這樣可以非常明顯的節省內存開銷,但要記住一個前提,在節省內存的同時,我們是加大了代碼運行時間為前提的,所以,有的時候我們需要平衡時間和內存開銷。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。