手机
当前位置:查字典教程网 >编程开发 >Java >轻松掌握Java享元模式
轻松掌握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; } }

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持查字典教程网。

【轻松掌握Java享元模式】相关文章:

java中String的一些方法深入解析

java中UDP简单聊天程序实例代码

使用Java实现系统托盘功能的介绍(附源码以及截图)

java中的Io(input与output)操作总结(四)

java多线程中的异常处理机制简析

浅析java中Integer传参方式的问题

jcrop 网页截图工具(插件)开发

Java中 URL实现断点下载

二进制中1的个数

Java代码重构的几种模式详解

精品推荐
分类导航