design patterns : flyweight

This commit is contained in:
haerong22
2021-12-10 00:44:36 +09:00
parent 9cfe1533a0
commit faba67f357
6 changed files with 101 additions and 0 deletions

View File

@@ -0,0 +1,16 @@
package flyweight.after;
public class Character {
private char value;
private String color;
private Font font;
public Character(char value, String color, Font font) {
this.value = value;
this.color = color;
this.font = font;
}
}

View File

@@ -0,0 +1,13 @@
package flyweight.after;
public class Client {
public static void main(String[] args) {
FontFactory fontFactory = new FontFactory();
Character c1 = new Character('h', "white", fontFactory.getFont("nanum:12"));
Character c2 = new Character('e', "white", fontFactory.getFont("nanum:12"));
Character c3 = new Character('l', "white", fontFactory.getFont("nanum:12"));
Character c4 = new Character('l', "white", fontFactory.getFont("nanum:12"));
Character c5 = new Character('o', "white", fontFactory.getFont("nanum:12"));
}
}

View File

@@ -0,0 +1,21 @@
package flyweight.after;
public final class Font {
final String family;
final int size;
public Font(String family, int size) {
this.family = family;
this.size = size;
}
public String getFamily() {
return family;
}
public int getSize() {
return size;
}
}

View File

@@ -0,0 +1,20 @@
package flyweight.after;
import java.util.HashMap;
import java.util.Map;
public class FontFactory {
private final Map<String, Font> cache = new HashMap<>();
public Font getFont(String font) {
if (cache.containsKey(font)) {
return cache.get(font);
} else {
String[] split = font.split(":");
Font newFont = new Font(split[0], Integer.parseInt(split[1]));
cache.put(font, newFont);
return newFont;
}
}
}

View File

@@ -0,0 +1,19 @@
package flyweight.before;
public class Character {
private char value;
private String color;
private String fontFamily;
private int fontSize;
public Character(char value, String color, String fontFamily, int fontSize) {
this.value = value;
this.color = color;
this.fontFamily = fontFamily;
this.fontSize = fontSize;
}
}

View File

@@ -0,0 +1,12 @@
package flyweight.before;
public class Client {
public static void main(String[] args) {
Character c1 = new Character('h', "white", "Nanum", 12);
Character c2 = new Character('e', "white", "Nanum", 12);
Character c3 = new Character('l', "white", "Nanum", 12);
Character c4 = new Character('l', "white", "Nanum", 12);
Character c5 = new Character('o', "white", "Nanum", 12);
}
}