java23種設計模式十(連載)

10、享元模式
java

        享元模式(Flyweight Pattern)顧名思義,就是多個對象共享一個對象,即共用一個內存地址,在實際應用中,採用享元模式的好處就是能夠大大節約內存空間,提升系統的運行效率。享元模式常常會出如今工廠模式當中,下面是具體的實現代碼:ide

首先建立一個享元類:測試

public abstract class Flyweight {

	public abstract void operation();
}

/**
 * 具體的享元類
 * @author Lynn
 *
 */
public class ConcreteFlyweight extends Flyweight {

	private String str;
	public ConcreteFlyweight(String str){
		this.str = str;
	}
	
	@Override
	public void operation() {
		System.out.println(str);
	}

}

而後建立一個工廠類,用於實體化享元類:

import java.util.Hashtable;

public class FlyweightFactory {

	private Hashtable<Object, Flyweight> flyweights = new Hashtable<>();
	public Flyweight getFlyweight(Object obj){
		Flyweight flyweight = flyweights.get(obj);
		if(null == flyweight){
			flyweight = new ConcreteFlyweight((String)obj);
			flyweights.put(obj, flyweight);
		}
		return flyweight;
	}
	
	public int getFlyweightSize(){
		return flyweights.size();
	}
}

這裏採用hashtable保存每一個享元對象,以便下次直接使用,下面是測試方法:

public class Client {

	FlyweightFactory factory = new FlyweightFactory();   
	Flyweight fly1;  
	Flyweight fly2;  
	Flyweight fly3;  
	Flyweight fly4;  
	Flyweight fly5;  
	Flyweight fly6;  

	public Client(){  
		fly1 = factory.getFlyweight("1");  
		fly2 = factory.getFlyweight("2");  
		fly3 = factory.getFlyweight("1");  
		fly4 = factory.getFlyweight("1");  
		fly5 = factory.getFlyweight("1");  
		fly6 = factory.getFlyweight("1");  
	}  
	public void showFlyweight(){  
		fly1.operation();  
		fly2.operation();  
		fly3.operation();  
		fly4.operation();  
		fly5.operation();  
		fly6.operation();  
		int size = factory.getFlyweightSize();  
		System.out.println("size = " + size);  
	}  
	public static void main(String[] args){  
		Client client = new Client();  
		client.showFlyweight();  
	}  
}
這樣實際上只建立了兩個對象,key 爲1和key爲2的

1
2
1
1
1
1
size = 2
在java中,String就是一個典型的採用享元模式的例子,String是final的,不能被繼承的,它也是不可變的,每次建立字符串對象都會保存到對象池中,下次使用到直接從對象池中取出字符串,而不會從新構建對象,下面的例子你們應該不陌生,

String a = "abc";this

String b = "abc";spa

System.out.println(a==b);code

「=」是比較的內存地址,這個例子當中打印爲true,說明他們的內存地址同樣,也就是都指向一個地址,即共享了一個對象。
對象

相關文章
相關標籤/搜索