Skip to content

Commit b6112b1

Browse files
authored
享元模式
享元模式
1 parent 4842fc4 commit b6112b1

File tree

4 files changed

+77
-0
lines changed

4 files changed

+77
-0
lines changed
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package com.java.design.flyweight;
2+
3+
public interface FlyWeight {
4+
5+
void showIndex(Integer index);
6+
7+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.java.design.flyweight;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
public class FlyWeightFactory {
7+
8+
private static Map<Integer, FlyWeight> map = new HashMap<Integer, FlyWeight>();
9+
10+
public FlyWeightFactory(Integer index) {
11+
12+
map.put(index, new FlyWeightImpl());
13+
}
14+
15+
public static FlyWeight getFlyWeight(Integer index) {
16+
if (!map.containsKey(index)) {
17+
18+
map.put(index, new FlyWeightImpl());
19+
}
20+
21+
return map.get(index);
22+
}
23+
24+
public static Integer getSize() {
25+
return map.size();
26+
}
27+
28+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package com.java.design.flyweight;
2+
3+
public class FlyWeightImpl implements FlyWeight {
4+
5+
@Override
6+
public void showIndex(Integer index) {
7+
8+
System.out.println("Index : " + index);
9+
}
10+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.java.design.flyweight;
2+
3+
/**
4+
* 享元模式(Flyweight Pattern) --↓↓↓---
5+
* 运用共享技术有效地支持大量细粒度对象的复用。系统只使用少量的对象,而这些对象都很相似,状态变化很小
6+
* ,可以实现对象的多次复用。由于享元模式要求能够共享的对象必须是细粒度对象,因此它又称为轻量级模式,它是一种对象结构型模式。
7+
*
8+
* @author Administrator
9+
*
10+
*/
11+
public class FlyweightPattern {
12+
13+
public static void main(String[] args) {
14+
15+
FlyWeight flyWeight = FlyWeightFactory.getFlyWeight(1);
16+
FlyWeight flyWeight2 = FlyWeightFactory.getFlyWeight(1);
17+
System.out.println("is the same ? ---> : " + (flyWeight == flyWeight2));
18+
19+
FlyWeight flyWeight3 = FlyWeightFactory.getFlyWeight(3);
20+
flyWeight3.showIndex(3);
21+
22+
FlyWeight flyWeight4 = FlyWeightFactory.getFlyWeight(4);
23+
flyWeight4.showIndex(4);
24+
25+
FlyWeight flyWeight5 = FlyWeightFactory.getFlyWeight(5);
26+
flyWeight5.showIndex(5);
27+
28+
System.out.println("map size is : " + FlyWeightFactory.getSize());
29+
30+
}
31+
32+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy