Flyweight
Flyweight ํจํด์ ์๋ง์ ๊ฐ์ฒด๋ฅผ ์์ฑํด์ผ ํ๋ ์ํฉ์์ ๋ฉ๋ชจ๋ฆฌ ์ฌ์ฉ์ ์ค์ด๊ณ ์ฑ๋ฅ์ ๊ฐ์ ํ๊ธฐ ์ํ ๋์์ธ ํจํด์ ๋๋ค. ์ด ํจํด์ ํต์ฌ ์์ด๋์ด๋ ๋์ผํ ์ํ๋ฅผ ๊ฐ์ง๋ ๊ฐ์ฒด๋ฅผ ์ฌ๋ฌ ๋ฒ ์์ฑํ๋ ๋์ , ์ด๋ฏธ ์์ฑ๋ ๊ฐ์ฒด๋ฅผ ์ฌ์ฌ์ฉ(๊ณต์ )ํ๋ ๋ฐฉ์์ ์์ต๋๋ค.
+----------------+
| Flyweight | <-- ๊ณตํต ์ธํฐํ์ด์ค
+----------------+
โฒ
โ
+-----------------------+
| ConcreteFlyweight | <-- ์ค์ ๊ฐ์ฒด (๊ณต์ ๋์)
+-----------------------+
โฒ
โ
+-----------------------+
| FlyweightFactory | <-- ๊ฐ์ฒด ์์ฑ ๋ฐ ๊ณต์ ๊ด๋ฆฌ
+-----------------------+
์บ์(cache)๋ ํ(pool) ๋ฐฉ์์์ ์ด๋ฏธ ์กด์ฌํ๋ id๋ฅผ ๊ฐ์ง ๊ฐ์ฒด๊ฐ ์๋ค๋ฉด ์ ๊ฐ์ฒด๋ฅผ ์์ฑํ์ง ์๊ณ ํด๋น ๊ฐ์ฒด๋ฅผ ๋ฐํํฉ๋๋ค. ๋ง์ฝ ํด๋น ๊ฐ์ฒด๊ฐ ์๋ค๋ฉด ์๋ก ์์ฑํ์ฌ ์ ์ฅํ ํ ๋ฐํํ๋ ๋ฐฉ์์ ๋๋ค.
๊ธฐ์กด์ id๋ฅผ ๊ฐ์ง ๊ฐ์ด ์์ผ๋ฉด ๊ทธ๊ฐ์ ์ฃผ๊ณ ์์ผ๋ฉด ์๋กญ๊ฒ ๊ฐ์ฒด๋ฅผ ๋ง๋ค๊ณ ์ถ๊ฐํด์ ์ฃผ๋(๊ณต์ ) ๋ฐฉ์์ ๋๋ค. Java์ ์ฌ๋ฌ Cache ์์ ์ฌ์ฉ๋๊ณ ์๋ ๋ฐฉ์์ ๋๋ค.
How do code
public interface Flyweight {
void operation();
}
// ๊ตฌ์ฒด์ ์ธ Flyweight ํด๋์ค
public class ConcreteFlyweight implements Flyweight {
private final String id;
public ConcreteFlyweight(String id) {
this.id = id;
}
@Override
public void operation() {
System.out.println("Flyweight ๊ฐ์ฒด " + id + "์ ์์
์ํ");
}
}
public class FlyweightFactory {
// ์ด๋ฏธ ์์ฑ๋ ๊ฐ์ฒด๋ค์ ์ ์ฅํ๋ ์บ์
private static final Map<String, Flyweight> pool = new HashMap<>();
// id๋ฅผ ๊ธฐ๋ฐ์ผ๋ก Flyweight ๊ฐ์ฒด๋ฅผ ๋ฐํํ๋ ๋ฉ์๋
public static Flyweight getFlyweight(String id) {
if (pool.containsKey(id)) {
return pool.get(id);
} else {
Flyweight flyweight = new ConcreteFlyweight(id);
pool.put(id, flyweight);
return flyweight;
}
}
}
Last updated