2019年5月13日 星期一

7天學會設計模式 CHAP24 蠅量級(享元)模式 FlyWeight

7天學會設計模式
http://www.books.com.tw/products/0010750585

chap24.
蠅量級(享元)模式 FlyWeight
目的:大量物件共享一些共同性質,降低系統的負荷
package com.ssc24.chap24.demo01;
public class Tree {
 private String type;
 private String owner;
 public Tree(String type) {
  this.type = type;
 }
 public void setOwner(String owner) {
  this.owner = owner;
 }
 public void display() {
  System.out.println(type + " ,擁有者" + owner);
 }
}

package com.ssc24.chap24.demo01;
import java.util.HashMap;
import java.util.Map;
public class TreeManager {
 private static Map<String,Tree> treePool = new HashMap<>();
 public static Tree getTree(String type) {
  if (!treePool.containsKey(type)) {
   treePool.put(type,new Tree(type));
  }
  return treePool.get(type);
 }
}

package com.ssc24.chap24.demo01;
import static org.junit.Assert.*;
import org.junit.Test;
public class TreeTest {
 @Test
 public void test() {
  System.out.println("===蠅量級模式測試===");
  Tree rose = TreeManager.getTree("玫瑰");
  rose.setOwner("Rose");
  rose.display();
  System.out.println("Jacky 來買一棵玫瑰花");
  Tree jRose = TreeManager.getTree("玫瑰");
  jRose.setOwner("Jacky");
  jRose.display();
  Tree hinoki = TreeManager.getTree("台灣紅檜");
  hinoki.setOwner("林務局");
  hinoki.display();
 }
}

/**
===蠅量級模式測試===
玫瑰 ,擁有者Rose
Jacky 來買一棵玫瑰花
玫瑰 ,擁有者Jacky
台灣紅檜 ,擁有者林務局
**/