-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathflyweight.java
More file actions
81 lines (64 loc) · 2.24 KB
/
flyweight.java
File metadata and controls
81 lines (64 loc) · 2.24 KB
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
import java.util.HashMap;
class WebsiteFactory {
/* 內部狀態 */
private final HashMap<String, Website> websiteCategory = new HashMap<>();
public Website getWebsiteCategory(String key){
if(!websiteCategory.containsKey(key))
websiteCategory.put(key, new ConcreteWebsite(key));
return websiteCategory.get(key);
}
public int getWebsiteCategoryCount(){
return websiteCategory.size();
}
}
interface Website {
void run(User user);
}
class ConcreteWebsite implements Website{
private String name;
public ConcreteWebsite(String name) {
this.name = name;
}
@Override
public void run(User user) {
System.out.printf("This website is %s which run by %s(id: %d)\n", this.name, user.getName(), user.getId());
}
}
/* 外部狀態(用來區分內部狀態)*/
class User {
private String name;
private int id;
public User(String name, int id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
public class Main {
public static void main(String[] args){
WebsiteFactory websiteFactory = new WebsiteFactory();
Website website1 = websiteFactory.getWebsiteCategory("產品展示");
website1.run(new User("Yik Ming", 1));
Website website2 = websiteFactory.getWebsiteCategory("產品展示");
website2.run(new User("Sing Lek", 2));
Website website3 = websiteFactory.getWebsiteCategory("產品展示");
website3.run(new User("Jason Lee", 3));
Website website4 = websiteFactory.getWebsiteCategory("部落格");
website4.run(new User("Ting Ye", 4));
Website website5 = websiteFactory.getWebsiteCategory("部落格");
website5.run(new User("Rui Quan", 5));
/* 即使有5個網站,但他們有些屬於同一個類型,所以Website物件(Flyweight物件)使同一類型的網站共享,所以數量不是5而是2 */
System.out.printf("website's category count: %d\n", websiteFactory.getWebsiteCategoryCount());
}
}