一、享元模式(FlyWeight,轻量级)
【共享类与非共享类】
/*** *FlyweightFactory享元工厂类: 创建并管理享元对象,享元池一般设计成键值对 */ package cn.sxt.flyWeight; import java.util.HashMap; import java.util.Map; public class ChessFactory { //享元池,容器 private static Map<String, Chess> map=new HashMap<String, Chess>(); public static Chess getChess(String color) { if (map.get(color)!=null) {//如果池子里边有那种颜色的棋子,返回一个即可,如果没有创建一个 return map.get(color); }else { Chess cfwChess=new ConcreteChess(color); map.put(color, cfwChess); return cfwChess; } } } /*** * 位置坐标,外部状态 UnsharedConcreteFlyWeight非共享享元类 * 不能被共享的子类可以设计为非共享享元类 */ package cn.sxt.flyWeight; public class Coordinate { private int x,y; public Coordinate(int x, int y) { super(); this.x = x; this.y = y; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } }
【享元工厂】
/*** *FlyweightFactory享元工厂类: 创建并管理享元对象,享元池一般设计成键值对 */ package cn.sxt.flyWeight; import java.util.HashMap; import java.util.Map; public class ChessFactory { //享元池,容器 private static Map<String, Chess> map=new HashMap<String, Chess>(); public static Chess getChess(String color) { if (map.get(color)!=null) {//如果池子里边有那种颜色的棋子,返回一个即可,如果没有创建一个 return map.get(color); }else { Chess cfwChess=new ConcreteChess(color); map.put(color, cfwChess); return cfwChess; } } }
【客户端】
/** * */ package cn.sxt.flyWeight; public class Client { public static void main(String[] args) { Chess chess1=ChessFactory.getChess("黑色"); Chess chess2=ChessFactory.getChess("黑色"); System.out.println(chess1); System.out.println(chess2);//输出结果与chess1的结果一样,说明它们共享一个引用对象 //增加外部状态的处理,加坐标 chess1.display(new Coordinate(10, 7)); chess2.display(new Coordinate(5, 7)); } }
【UML类图】
二、7种结构模式总结