这里有新鲜出炉的Java并发编程示例,程序狗速度看过来!
java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由Sun Microsystems公司于1995年5月推出的Java程序设计语言和Java平台(即JavaEE(j2ee), JavaME(j2me), JavaSE(j2se))的总称。
这篇文章主要帮助大家轻松掌握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;
- }
- }
享元模式主要为了解决大量类似对象占用大量内存的现象,因为内存是珍贵的资源,所以我们讲这些相似对象进行归类,提取出相同部分用以共享,这样可以非常明显的节省内存开销,但要记住一个前提,在节省内存的同时,我们是加大了代码运行时间为前提的,所以,有的时候我们需要平衡时间和内存开销。
来源: http://www.phperz.com/article/17/1115/359834.html