java享元模式+工厂模式+单例模式,减少new对象的个数,减少内存中堆的消耗

长话短说
······在我看来,是这3个模式组成了享元模式
······享元模式的优点是:减少相同对象的船舰
······工厂模式在这个设计模式起到了管理对象的作用
······单例模式(多对象单例)这个是享元模式的核心。决定了相同的对象不用重复创建
······这又是一个面向接口的编程,享元模式可以减少相同的对象创建。相同的对象就是对象类型相同并且对象的内部属性相同,比如一个对象里面只放了一个String,如果2个对象放的Sting是equals的,那么就可以认为这两个对象是相同的对象。这2个对象中有任何不形同的点,就不能算是相同的对象,就不能用享元模式(针对对象而言)
······代码举例环节,该代码的展示了,3种不同颜色的Circle(圆形),被创建的过程
首先是一个接口Shape(形状)

public interface Shape {
	void draw();
}

然后是接口的实现

public class Circle implements Shape {
	
	private String color;
	
	private static int j = 1;//记录对象创建的个数
	
	public Circle() {
		//如果这句话没有输出,说明程序没有悄悄的自己通过无参构造创建对象
		System.out.println("通过无参构造new对象");
	}
	
	public Circle(String color) {
		System.out.println("new object:" + j);
		j++;
	}
	@Override
	public void draw() {
		// TODO Auto-generated method stub
		System.out.println("color is:" + color);
	}
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
}

接下来是工厂+多对象单例类(享元模式核心类)

public class ShapeFactory {

	//讲多个对象放进Map管理,该对象的关键字为key,该对象为value
	public static Map<String, Shape> cirlceMap =
			new HashMap<String, Shape>();
	
	public static Shape getCircles(String color) {
		Shape circle = (Shape) cirlceMap.get(color);
		//如果map里面没有该对象,才会创建对象
		if (circle == null) {
			circle = new Circle(color);
			cirlceMap.put(color, circle);
			System.out.println("Creating circle of color:" + color);
		}
		return circle;
	}
}

测试类

public class Test {

	private static String colors[] =
		{"Red", "Green", "Blue"};
	
	public static void main(String[] args) {
		for (int i = 0 ; i < 10 ; i++) {
			Shape circle = (Shape)ShapeFactory.getCircles(getRandomCircle());
			circle.draw();
		}
	}
	
	private static String getRandomCircle() {
		return colors[(int) (Math.random()*colors.length)];
	}
}

控制台输出

new object:1
Creating circle of color:Green
color is:null
new object:2
Creating circle of color:Blue
color is:null
color is:null
color is:null
color is:null
color is:null
color is:null
new object:3
Creating circle of color:Red
color is:null
color is:null
color is:null

从控制台输出可以看出,本来是需要创建10个对象,但是真正创建的对象只有3个,其他的都是相同的对象,是不会被创建的。用的时候只需要直接引用原来创建好的对象就可以

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值