---
title: "设计模式-享元模式"
author: "DanielHan"
date: "2014-02-12T08:53:22Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2014-02-12T08:54:06Z"
id: 2015069
url: "https://danielhan.iteye.com/blog/2015069"
---

享元模式（Flyweight Pattern）
享元模式，以共享的方式高效地支持大量的细粒度对象。通过复用内存中已存在的对象，降低系统创建对象实例的性能消耗。

以黑白五子棋为例

```java

public abstract class Chessman {

	private String color;
	private int x;
	private int y;
	
	public Chessman(String color){
		this.color=color;
	}
	
	//设置棋子位置
	public void setPosition(int x,int y){
		this.x=x;
		this.y=y;
	}

	public String getColor() {
		return color;
	}

	public int getX() {
		return x;
	}

	public int getY() {
		return y;
	}
}

```



```java

public class BlackChessman extends Chessman{
	public BlackChessman() {
		super("黑棋子");
		System.out.println("创建黑棋子");
	}
}

```



```java

public class WhiteChessman extends Chessman{
	public WhiteChessman() {
		super("白棋子");
		System.out.println("创建白棋子");
	}
}

```



```java

public class ChessmanFactory {
	private static ChessmanFactory ChessmanFactory=new ChessmanFactory();
	//缓存存放共享对象
	Hashtable<Character, Chessman> cache=new Hashtable<Character, Chessman>();
	
	public static ChessmanFactory getInstance(){
		return ChessmanFactory;
	}
	//获取棋子
	public Chessman getChessman(char c){
		Chessman chessman=this.cache.get(c);
		if(chessman==null){
			if(c=='W'){
				chessman=new WhiteChessman();
			}else if(c=='B'){
				chessman=new BlackChessman();
			}
			cache.put(c, chessman);
		}
		return chessman;
	}
}

```



```java

public class Demo {
	public static void main(String[] args) {
		ChessmanFactory factory=ChessmanFactory.getInstance();
		Chessman chessman1=factory.getChessman('W');
		chessman1.setPosition(1, 1);
		System.out.println(chessman1.getColor()+" ("+chessman1.getX()+","+chessman1.getY()+")");
		Chessman chessman2=factory.getChessman('W');
		chessman2.setPosition(2, 2);
		System.out.println(chessman2.getColor()+" ("+chessman2.getX()+","+chessman2.getY()+")");
		Chessman chessman3=factory.getChessman('B');
		chessman3.setPosition(3, 3);
		System.out.println(chessman3.getColor()+" ("+chessman3.getX()+","+chessman3.getY()+")");
		Chessman chessman4=factory.getChessman('B');
		chessman4.setPosition(4, 4);
		System.out.println(chessman4.getColor()+" ("+chessman4.getX()+","+chessman4.getY()+")");
	}
}

```


测试结果

```java

创建白棋子
白棋子 (1,1)
白棋子 (2,2)
创建黑棋子
黑棋子 (3,3)
黑棋子 (4,4)

```


享元模式的两种状态：内蕴状态和外蕴状态
1.内蕴状态：
  享元模式的内蕴状态是不会随环境的改变而改变的，是存储在享元对象内部的状态信息，因此内蕴状态是可以共享的，对于任何一个享元对象来讲，它的值是完全相同的。就像上面例子中的“黑子”和“白子”，它代表的状态就是内蕴状态。
2.外蕴状态
  外蕴状态会随环境的变化而改变的，因此是不可共享的状态，对于不同的享元对象来讲，它的值可能是不同的。享元对象的外蕴状态必须由客户端保存，在享元对象被创建之后，需要使用的时候再传入到享元对象的内部。就像五子棋的位置信息，代表的状态就是享元对象的外蕴状态。