简介
一、定义
1、概念
- 享元(Flyweight)模式:运用共享技术有效地支持大量细粒度对象的复用,是一种结构型模式。
2、理解
- 可以设计为享元对象的是相似度高、状态变化小,需要多次复用的细粒度对象;
- 设计享元对象是核心,关键在于内外部状态的分离,内部状态自行设置,外部状态需要运行传入(可以将外部状态设计为一个类);
二、组件
- Flyweight(抽象享元类):一个接口或抽象类,声明了具体享元类的公共方法。
- ConcreteFlyweight(具体享元类):实现了抽象享元类,其实例称为享元对象。
- UnsharedConcreteFlyweight(非共享具体享元类):并不是所有的抽象享元类的子类都需要被共享,不能被共享的子类可设计为非共享具体享元类。
- FlyweightFactory(享元工厂类):用于创建并管理享元对象,一般设计为一个存储 Key-Value 键值对的集合(可以结合工厂模式设计)。其作用就在于:提供一个用于存储享元对象的享元池,当用户需要对象时,首先从享元池中获取,如果享元池中不存在,那么则创建一个新的享元对象返回给用户,并在享元池中保存该新增对象。
三、结构图
示例(围棋)
一、外部状态类
public class Cordinate { private int x; private int y; public Cordinate(int x, int y) { 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; } @Override public String toString() { return "(" + "x=" + x + ", y=" + y + ')'; } }
二、抽象 & 具体享元类
public abstract class Chess { public abstract String getColor(); public void display(Cordinate cordinate){ System.out.println("chess color:"+this.getColor()+"------cordinate:"+cordinate); } } public class WhiteChess extends Chess { @Override public String getColor() { return "white"; } } public class BlackChess extends Chess { @Override public String getColor() { return "black"; } }
三、享元工厂(简单工厂)
public class ChessFactory { private static ChessFactory factory = new ChessFactory(); private static HashMap chessPool; private ChessFactory() { chessPool = new HashMap(); chessPool.put("white",new WhiteChess()); chessPool.put("black",new BlackChess()); } public static Chess getChess(String color){ return (Chess) chessPool.get(color); } }
四、客户端代码
public class Client { public static void main(String[] args) { Cordinate c1,c2,c3,c4; c1= new Cordinate(12,12); c2= new Cordinate(13,13); c3= new Cordinate(14,12); c4= new Cordinate(12,15); Chess b1,b2,w1,w2; b1 = ChessFactory.getChess("black"); b2 = ChessFactory.getChess("black"); w1 = ChessFactory.getChess("white"); w2 = ChessFactory.getChess("white"); System.out.println("b1=b2:"+(b1==b2)); System.out.println("w1=w2:"+(w1==w2)); b1.display(c1); b2.display(c2); w1.display(c3); w2.display(c4); } }
总结
一、优缺点
- 优点:可以极大减少内存中对象的数量,使得相同或相似对象在内存中只有一份 ,节省系统资源提高性能
- 缺点:为了使对象可以共享,享元模式需要将享元对象的部分状态外部化,而读取外部状态将使得运行时间变长
二、使用场景
- 一个系统有大量相同或相似的对象,造成了系统内存的大量损耗
- 对象的大部分状态都可以外部化,可以将这些外部状态传入对象中。
- 要维护享元模式,需要耗费一定的系统资源,因为在需要时会多次重复使用才值得使用享元模式了!