当前位置: 移动技术网 > IT编程>开发语言>Java > 轻松掌握Java享元模式

轻松掌握Java享元模式

2019年07月22日  | 移动技术网IT编程  | 我要评论

阿拉伯语歌曲,赵尔陆,e03008

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

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

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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网