轻松掌握Java享元模式

网友投稿 171 2023-07-04


轻松掌握Java享元模式

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

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

企业级开发及常用框架中的应用:数据库的连接池,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 radiusUIlGpXky;

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 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;

}

}

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


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:java增强for循环的实现方法
下一篇:关于List.ToArray()方法的效率测试
相关文章

 发表评论

暂时没有评论,来抢沙发吧~