본문 바로가기

강의/Design pattern

플라이웨이트 (Flyweight) 패턴

SMALL

https://velog.io/@sillutt/%ED%94%8C%EB%9D%BC%EC%9D%B4%EC%9B%A8%EC%9D%B4Flyway-%ED%8C%A8%ED%84%B4-ss6ti9tj

 

플라이웨이(Flyway) 패턴

플라이웨이 패턴

velog.io

Flyweight 패턴

애플리케이션에서 많은 인스턴스를 생성하는 중에 사용할 수 있는 패턴이다. 인스턴스를 많이 사용하면 OutOfMemory, 즉 메모리가 부족한 현상이 발생하는데, 따로 모아서 재사용할 수 있는 패턴이다. 자주 사용하는 속성(extrinsit)과 그렇지 않은 속성(intrinsit)을 분리하여 자주 변경되지 않는 속성을 재사용한다.


Code

Flyweight의 속성은 immutable 해야 한다. 즉, 이 인스턴스의 값을 임의로 변경할 수 없다. 다른 인스턴스에도 공유되는 데이터이기 때문이다. Java에서는 final 키워드로 immutable을 유지할 수 있다.

Font

// Flyweight
public final class Font { //상속 방지
	final String family;
	final int size;
	//getter, setter, constructor
}

Charater

public class Character {
	private char value;
	private String color;
	private Font font

	//constructor
}

FontFactory

flyweight의 인스턴스에 접근하고 캐싱하는 역할을 한다.

public class FontFactory {
	private Mat<String, Font> cache = new HashMap<>();
	puboic Font getFont(String font) {
		if(cache.containKey(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;
		}
	}
}

Client

public class Clinet {
	public static void main(String[] args) {
		FontFactory fontFactory = new FontFactory();
		Character c1 = new Character("h", "white", fontFactory.getfont("namu:12"));
		//...
	}
}

장단점

장점

  • 애플리케이션에서 사용하는 메모리를 줄일 수 있다.

단점

  • 코드의 복잡도가 증가한다.

Example

도메인에서의 특정된 부분을 간추리는데 사용하는 패턴이기 때문에 라이브러리나 프레임워크에서 찾기는 쉽지 않다.

valuOf

Integer i1 = Integer.valueOf(10);

자주사용되는 값들을 캐싱해서 값을 반환한다.

SMALL

'강의 > Design pattern' 카테고리의 다른 글

책임 연쇄 패턴  (0) 2022.09.22
프록시(Proxy) 패턴  (0) 2022.09.22
퍼싸드(Facade) 패턴  (0) 2022.08.16
브릿지 (Bridge) 패턴  (0) 2022.08.16
어댑터 (Adapter) 패턴  (0) 2022.08.16