设计模式——享元模式

文章介绍了享元模式的概念,它用于有效地支持大量细粒度对象,通过共享技术减少内存使用。文章提供了具体的Java实现,包括抽象享元接口、具体享元类和享元工厂,以及一个测试类来展示如何在系统中有大量相似对象时使用享元模式。享元模式的优点在于减少对象创建,提高系统效率,但也会增加系统复杂性。
摘要由CSDN通过智能技术生成

1.定义

运用共享技术有效支持大量细粒度对象。

2.使用场景

1、系统有大量相似对象。 2、需要缓冲池的场景。
例如: 1、JAVA 中的 String,如果有则返回,如果没有则创建一个字符串保存在字符串缓存池里面。 2、数据库的连接池。

3.实现

/**
 *  抽象享元(Flyweight)角色:是所有的具体享元类的基类,为具体享元规范需要实现的公共接口,非享元的外部状态以参数的形式通过方法传入。
 * @author Administrator
 *
 */
public interface Shape {
	void draw();
}
/**
 * 具体享元(Concrete Flyweight)角色:实现抽象享元角色中所规定的接口。
 * @author Administrator
 *
 */
public class CircleShape implements Shape{
	private String color;
	private int x;
	private int y;
	private int radius;
	
	public CircleShape(String color) {
		// TODO Auto-generated constructor stub
		this.color = color;
	}
	
	public void setRadius(int radius) {
		this.radius = radius;
	}
	
	public void setX(int x) {
		this.x = x;
	}
	
	public void setY(int y) {
		this.y = y;
	}
	
	@Override
	public void draw() {
		// TODO Auto-generated method stub
		System.out.println("draw a circle[color="+color+",x="+x+",y="+y+",radius="+radius);
	}

}
/**
 * 享元工厂(Flyweight Factory)角色:负责创建和管理享元角色。当客户对象请求一个享元对象时,
 * 享元工厂检査系统中是否存在符合要求的享元对象,如果存在则提供给客户;如果不存在的话,则创建一个新的享元对象。
 * @author Administrator
 *
 */
public class FlyWeightFactory {
	private static HashMap<String,Shape> hashMap = new HashMap<>();
	
	public static Shape getShape(String color) {
		CircleShape shape = (CircleShape)hashMap.get(color);
		if(shape==null) {
			shape = new CircleShape(color);
			hashMap.put(color, shape);
			System.out.println("Creating circle of color : " + color);
		}
		
		return shape;
	}

}
/**
 * 测试类
 * @author Administrator
 *
 */
public class Test {
	private final static String[] colors = new String[] {"red","green","yellow"};
	
	public static void main(String[] args) {
		for(int i=0;i<10;i++) {
			CircleShape circle = (CircleShape)FlyWeightFactory.getShape(getRandomColor());
			circle.setRadius(2);
			circle.setX(getRandomX());
			circle.setY(getRandomY());
			circle.draw();
		}
	}
	
	private static String getRandomColor() {
	      return colors[(int)(Math.random()*colors.length)];
	   }
	   private static int getRandomX() {
	      return (int)(Math.random()*100 );
	   }
	   private static int getRandomY() {
	      return (int)(Math.random()*100);
	   }
}

运行结果
在这里插入图片描述

4.总结

在有大量对象时,有可能会造成内存溢出,我们把其中共同的部分抽象出来,如果有相同的业务请求,直接返回在内存中已有的对象,避免重新创建。

优点: 大大减少对象的创建,降低系统的内存,使效率提高。
缺点: 提高了系统的复杂度,需要分离出外部状态和内部状态,而且外部状态具有固有化的性质,不应该随着内部状态的变化而变化,否则会造成系统的混乱。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值