Java设计模式之享元模式

定义:它使用共享物件,用来尽可能减少内存使用量以及分享资讯给尽可能多的相似物件;它适合用于只是因重复而导致使用无法令人接受的大量内存的大量物件。

特点:大大减少对象的创建,降低系统的内存,使效率提高。

企业级开发及常用框架中的应用:数据库的连接池,String的常量缓存池

具体代码实例:

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

public class Demo {

	public static void main(String[] args) {
		for(int i = 0 ; i < 10 ; i++){
			Circle circle = new Circle(getColor());
			circle.setRadius(getRadius());
			circle.setX(getZ());
			circle.setY(getZ());
			circle.draw();
		}
	}
	
	public static String getColor(){
		String[] colors = {"红色","橙色","黄色","青色","绿色"};
		Random random = new Random();
		int index = random.nextInt(4);
		return colors[index];
	}
	
	public static double getRadius(){
		Random random = new Random();
		return  random.nextDouble()*20;
	}
	
	public static int getZ(){
		Random random = new Random();
		return random.nextInt(100);
	}
}

/**
 * 抽象享元类
 * 这里以画图形举例:比如画圆,加入颜色固定,画圆的方式都是一样的,所不同的就是圆形的位置和圆的半径
 */
interface Shape{
	public void draw();
}

/**
 *	具体享元类 
 *	这里创建具体的享元类,类中包含了可以共享的数据和不可共享的数据
 *	例如:可以共享的颜色以及隐形的画圆方式,不可共享的半径和坐标
 */
class Circle implements Shape{

	private int x;
	private int y;
	private double radius;
	private String color;
	
	public Circle(String color) {
		this.color = color;
	}

	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 double getRadius() {
		return radius;
	}

	public void setRadius(double radius) {
		this.radius = radius;
	}

	public String getColor() {
		return color;
	}

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

	public void draw() {
		System.out.println("画了一个圆心坐标为:("+this.x+","+this.y+"),半径为"+this.radius+","+this.color+"的圆");
	}
	
}

/**
 * 工厂类:享元模式的具体体现其实是在这一块得到实现的,在这一块我们可以清楚的了解到共享了哪些属性或者数据
 * 在这里假设圆的颜色是固定的,我们只能画固定的几种颜色的圆
 * 在这里例子中对应的共享数据就应该是对应的颜色属性和隐形的不可见的还原的方式,这个在前面交代过,所有圆的
 * 画的方式是一样的
 */
class CircleFactory{
	private static Map<String, Circle> map = new HashMap<>();
	
	public static Circle getCircle(String color){
		Circle c = map.get(color);
		if(c == null){
			c = new Circle(color);
			map.put(color, c);
			return c;
		}
		return c;
	}
}

享元模式主要为了解决大量类似对象占用大量内存的现象,因为内存是珍贵的资源,所以我们讲这些相似对象进行归类,提取出相同部分用以共享,这样可以非常明显的节省内存开销,但要记住一个前提,在节省内存的同时,其实我们是加大了代码运行时间为前提的,所以,有的时候我们需要平衡时间和内存开销。

转载于:https://my.oschina.net/jiaoy/blog/743907

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值