享元模式

**享元模式:**内存属于稀缺资源,不要随便浪费。如果有很多个完全相同或相似的
对象,我们可以通过享元模式,节省内存
在这里插入图片描述

如图 在图中每个棋子的颜色,大小是不会随着环境变换而变化的。这样的属性称之为内部状态,而每个棋子的位置是不同的 称之为外部状态。这也是享元对象能做到共享的关键区分内部状态和外部状态;
• 内部状态:可以共享,不会随环境变化而改变
• 外部状态:不可以共享,会随环境变化而改变

/**
 * 外部状态定义棋子的位置
 * @author 
 *
 */
public class Cordinate {
	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 Cordinate(int x, int y) {
		super();
		this.x = x;
		this.y = y;
	}
	public Cordinate() {
		super();
		// TODO Auto-generated constructor stub
	}
}


/**
 * 定棋子的颜色 
 * @author 
 *
 */
public class ConcreteChess {
	private String color;//内部状态 颜色
	
	public ConcreteChess() {
		super();
		// TODO Auto-generated constructor stub
	}

	public ConcreteChess(String color) {
		super();
		this.color = color;
	}

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}


	/**
	 * 展示小球的位置
	 * @param cordinate
	 */
	
	public void show(Cordinate cordinate) {
		System.out.println( "小球的颜色是"+this.color+"小球的位置是"+cordinate.getX()+"===="+cordinate.getY());
	}
	
}

享元工厂:


public class Factory {
    //定义容器
	private static  Map<String,ConcreteChess> map=new HashMap<String,ConcreteChess>();
	
	public static ConcreteChess getCordinat(String str) {
		if(map.get(str)!=null) {
			return map.get(str);
		}else {
			ConcreteChess c=new ConcreteChess(str);
			map.put(str, c);
			return c;
		}
	}
}

测试

public class Client {

	public static void main(String[] args) {
		
		ConcreteChess c=Factory.getCordinat("黑色");
		ConcreteChess c2=Factory.getCordinat("黑色");
		System.out.println(c==c2);
		c.show(new Cordinate(1, 8000));
	}

}

结果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值