亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

輕松掌握J(rèn)ava享元模式

 更新時(shí)間:2016年09月30日 11:57:31   作者:斷了聯(lián)系  
這篇文章主要幫助大家輕松掌握J(rèn)ava享元模式,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

定義:它使用共享物件,用來盡可能減少內(nèi)存使用量以及分享資訊給盡可能多的相似物件;它適合用于只是因重復(fù)而導(dǎo)致使用無(wú)法令人接受的大量?jī)?nèi)存的大量物件。

特點(diǎn):大大減少對(duì)象的創(chuàng)建,降低系統(tǒng)的內(nèi)存,使效率提高。

企業(yè)級(jí)開發(fā)及常用框架中的應(yīng)用:數(shù)據(jù)庫(kù)的連接池,String的常量緩存池

具體代碼實(shí)例:

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();
}

/**
 * 具體享元類 
 * 這里創(chuàng)建具體的享元類,類中包含了可以共享的數(shù)據(jù)和不可共享的數(shù)據(jù)
 * 例如:可以共享的顏色以及隱形的畫圓方式,不可共享的半徑和坐標(biāo)
 */
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("畫了一個(gè)圓心坐標(biāo)為:("+this.x+","+this.y+"),半徑為"+this.radius+","+this.color+"的圓");
 }
 
}

/**
 * 工廠類:享元模式的具體體現(xiàn)其實(shí)是在這一塊得到實(shí)現(xiàn)的,在這一塊我們可以清楚的了解到共享了哪些屬性或者數(shù)據(jù)
 * 在這里假設(shè)圓的顏色是固定的,我們只能畫固定的幾種顏色的圓
 * 在這里例子中對(duì)應(yīng)的共享數(shù)據(jù)就應(yīng)該是對(duì)應(yīng)的顏色屬性和隱形的不可見的還原的方式,這個(gè)在前面交代過,所有圓的
 * 畫的方式是一樣的
 */
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;
 }
}

享元模式主要為了解決大量類似對(duì)象占用大量?jī)?nèi)存的現(xiàn)象,因?yàn)閮?nèi)存是珍貴的資源,所以我們講這些相似對(duì)象進(jìn)行歸類,提取出相同部分用以共享,這樣可以非常明顯的節(jié)省內(nèi)存開銷,但要記住一個(gè)前提,在節(jié)省內(nèi)存的同時(shí),我們是加大了代碼運(yùn)行時(shí)間為前提的,所以,有的時(shí)候我們需要平衡時(shí)間和內(nèi)存開銷。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論