package cn.bunny.pattern18;

import lombok.Data;

import java.util.HashMap;
import java.util.Map;

public class FlyWeight {
    public static void main(String[] args) {
        // 第一次获取对象会进行资源创建
        GirlFriend girlFriend1 = GirlFriendFactory.getGirlFriend("第一个女朋友");
        GirlFriend girlFriend2 = GirlFriendFactory.getGirlFriend("第二个女朋友");

        // 第二次获取对象直接从容器中获取
        GirlFriend girlFriend11 = GirlFriendFactory.getGirlFriend("第一个女朋友");
        GirlFriend girlFriend22 = GirlFriendFactory.getGirlFriend("第二个女朋友");

        System.out.println(girlFriend1 == girlFriend11);// true
        System.out.println(girlFriend2 == girlFriend22);// true
    }

    @Data
    static class GirlFriend {
        private String name;
        private Integer age;
    }

    static class GirlFriendFactory {
        private static final Map<String, GirlFriend> map = new HashMap<>();

        public static GirlFriend getGirlFriend(String name) {
            GirlFriend girlFriend = map.get(name);
            if (girlFriend == null) {
                girlFriend = new GirlFriend();
                girlFriend.name = name;
                map.put(name, girlFriend);
            }
            return girlFriend;
        }
    }
}
