GOF23 设计模式 之享元模式

享元模式就是 如果有很多个一样或者相似的对象;提高它的复用性;节省内存( 可能存在 时间换空间上的问题,这个避免不了);

核心:1. 共享的方式支持大量细粒度的复用;

2. 享元 做到共享的关键 一是 内部状态(共享的状态) 二是外部状态(不可共享的状态)

********************

实现结构:

1. 享元工厂类

2,抽象享元类

3,具体享元类

4,非共享享元类

********************

代码实现:

坐标类

package FlyWeight;

// 坐标类
public class Coordinate {
	private int x,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;
	}

	public Coordinate(int x, int y) {
		super();
		this.x = x;
		this.y = y;
	}
	

}

享元类

package FlyWeight;

/**
 * 
 * 享元类接口
 * 
 * */
public interface ChessFlyWeight {  
	void setColor(String c);
	String getColor();
	void display(Coordinate c);
}

/**
 * 
 * 享元类
 * 
 * */
class ConCreateChess implements ChessFlyWeight{
	private String color;
	public ConCreateChess(String color) {
		super();
		this.color = color;  // 把颜色作为共享单元, 但是对于坐标作为不共享的单元
	}

	@Override
	public void setColor(String c) {
		// TODO Auto-generated method stub
		this.color = c;
	}

	@Override
	public String getColor() {
		// TODO Auto-generated method stub
		return color;
	}

	@Override
	public void display(Coordinate c) {
		// TODO Auto-generated method stub
		System.out.println("棋子的颜色是:" + this.color);
		System.out.println("棋子的坐标是x:"+c.getX()+"y:"+c.getY());
	}
	
}

享元工厂

package FlyWeight;

import java.util.HashMap;
import java.util.Map;

/**
 * 
 * 享元工厂类
 * 
 * */

public class ChessFlyWeightFactory {
	private static Map<String, ChessFlyWeight> map= new HashMap<String, ChessFlyWeight>();
	
	public ChessFlyWeight getChessFlyWeight (String color) { // 把颜色作为共享单元, 但是对于坐标作为不共享的单元
		if(map.get(color)==null) {
			ChessFlyWeight cfw= new ConCreateChess(color);
			map.put(color, cfw);
		}
		return map.get(color);
	}
}

客户端

package FlyWeight;

public class Client {
	public static void main(String[] args) {
		ChessFlyWeight chess1 =  new ChessFlyWeightFactory().getChessFlyWeight("black");
		ChessFlyWeight chess2 =  new ChessFlyWeightFactory().getChessFlyWeight("black");
		System.out.println(chess1);
		System.out.println(chess2);
		
		System.out.println("外部状态处理=======");
		chess1.display(new Coordinate(10, 20));
		chess1.display(new Coordinate(20, 40));
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值