模拟红黑旗子实现:
1 /** 2 *享元模式: 类似Interger包装类,在-128~127之间的小数,由不同的对象共享 3 * 就是把大量的,经常要用的对象中的不变内容封装到一个类中,而把那些不同的属性放到外面,需要用的时候再传给前者, 4 * 这样可以节省很多内存空间,正如一片英文文档,其中内容均为a~z等字母,我们不必也不能把各个字符创建成一个对象,试想一下,如果 5 * 这篇文档长达几万甚至几十万,那创建的对象不把内存给占死?文档中的字符都是一样的,所不同的是它们的位置, 6 * 所以,我们只需为每个字符创建一个对象,而将不同的坐标位置传给相应对象让其进行显示即可,这样可以大大节省内存空间, 7 * 实现享元要通过FlyWeightFactory来实现,如果所用对象已经存在,就直接用key得到该对象并返回 8 */ 9 public interface ChessFlyWeight { 10 void setColor(String color); 11 String getColor(); 12 void display(Point point); 13 } 14 15 class ConcreteChess implements ChessFlyWeight{ 16 public ConcreteChess(String color){ 17 this.color = color; 18 } 19 20 @Override 21 public void setColor(String color) { 22 this.color = color; 23 } 24 25 @Override 26 public String getColor() { 27 return color; 28 } 29 30 @Override 31 public void display(Point point) { 32 System.out.println("颜色: " + color + ", 位置:(" + point.getX() + "," + point.getY() + ")"); 33 } 34 35 private String color; 36 }
1 import java.util.concurrent.ConcurrentHashMap; 2 3 public class FlyWeightFactory { 4 public static ChessFlyWeight getChess(String color){ 5 if(chm.containsKey(color)){ 6 return chm.get(color); 7 } else{ 8 ChessFlyWeight cfw = new ConcreteChess(color); 9 chm.put(color, cfw); 10 return cfw; 11 } 12 } 13 14 //通过map确保使用同一个对象 15 private static ConcurrentHashMap<String, ChessFlyWeight> chm = new ConcurrentHashMap<>(); 16 }
1 public class Point { 2 public Point(){ 3 4 } 5 6 public Point(int x, int y) { 7 this.x = x; 8 this.y = y; 9 } 10 11 public int getX() { 12 return x; 13 } 14 15 public void setX(int x) { 16 this.x = x; 17 } 18 19 public int getY() { 20 return y; 21 } 22 23 public void setY(int y) { 24 this.y = y; 25 } 26 27 private int x; 28 private int y; 29 }
测试类:
1 public class Test { 2 public static void main(String[] args) { 3 ChessFlyWeight c = FlyWeightFactory.getChess("red"); 4 ChessFlyWeight c2 = FlyWeightFactory.getChess("red"); 5 System.out.println(c); 6 System.out.println(c2); 7 ChessFlyWeight c3 = FlyWeightFactory.getChess("black"); 8 System.out.println(c3); 9 } 10 }