Structure Array Structure Array:軽量レベルのアレイ


紹介する


オブジェクトを軽くし、メモリの使用パターンを減らします.
  • は、頻繁に変化する属性(または外在的属性)と不変の属性(または内在的属性)を分離して再利用することができ、メモリの使用を減らすことができる.
  • 1)メリット


    アプリケーションで使用されるメモリを削減できます.

    2)欠点


    コードの複雑さが増す.

    適用前

    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);
        }
    }

    インプリメンテーション


    1)工場の作成

    public class FontFactory {
    	
        private Map<String, Font> cache = new HashMap<>();
        
        public Font getFont(String font) {
        	if(cache.containsKey(font)) {
            	return cache.get(font);
            } else {
            	String[] splist = font.split(":");
                Font newFont = new Font(split[0], Integer.parseInt(split[1]));
                cache.put(font, newFont);
                return newFont;
            }
        }
    }

    2)内部要素の定義

    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;
        }
    }

    3)外部要素の定義

    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;
    	}
    }

    使用

    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");
        }
    }