標籤:參數 sha ttl 不同 span tle 申請 pattern 基本
代碼調優,實際上就是為了降低程式的時空代價。Flyweight Pattern允許在應用中不同部分共用使用objects,這個就可以大幅度的減少new的對象個數,降低大量objects帶來的時空代價。應用flyweight pattern的對象其可分為內部特徵(不管在什麼場合使用該ovject,內部特徵都不變)和外部特徵(不是固定的,需要在不同場合分別計算併產生變化)。這個外部特徵就保證了同一個對象可以在不同的場合進行應用,不同的場合需要不同的對象特性,我們就可以通過修改外部對象特徵的方式使同一個對象表現出不同的特徵。
下面我們給出一個關於機器人的對象的應用,其UML圖為:
IAlien介面的兩個實現,其主要的區別就是具有不同的形狀,這屬於內部屬性。同時,對於IAlien在不同位置的調用顯示出不同的狀態是通過Color確定的。而什麼顏色由傳入的參數確定,這個我們就可以再不同的位置對於IAlien傳入不同的參數,讓其顯示不同的狀態,使其應用一個對象完成多個對象的功能。Factory類,用於儲存新建立的對象,每次要對對象進行調用時,可以向Factory申請,此時Factory的作用和Object Pool基本相同。
下面給出代碼執行個體:
class LargeAlien implements IAlien{
private String Shape = "Large Shape";
public String getShape(){
return shape:
}
public Color getColor(int madlevel){
if(madlevel==0)
return Color.green;
else if(madlevel == 1)
return Color.red;
else
return Color.blue
}
}
class LittleAlien implements IAlien{
private String Shape = "Little Shape";
public String getShape(){
return shape:
}
public Color getColor(int madlevel){
if(madlevel==0)
return Color.green;
else if(madlevel == 1)
return Color.red;
else
return Color.blue
}
}
public class AlienFactory {
private Map<String, IAlien> list = new HashMap<>();
public void SaveAlien(String index, IAlien alien) {
list.put(index,alien);
}
public IAlien GetAlien(String index) {
return list.get(index);
}
}
AlienFactory factory = new AlienFactory();
factory.SaveAlien("LargeAlien", new LargeAlien());
factory.SaveAlien("LittleAlien", new LittleAlien());
IAlien a = factory.GetAlien("LargeAlien");
IAlien b = factory.GetAlien("LittleAlien");
System.out.println("Showing intrinsic states...");
System.out.println("Alien of type LargeAlien is " + a.getShape());
System.out.println("Alien of type LittleAlien is " + b.getShape());
System.out.println("Showing extrinsic states...");
System.out.println("Alien of type LargeAlien is " + a.getColor(0).toString());
System.out.println("Alien of type LargeAlien is " + a.getColor(1).toString());
System.out.println("Alien of type LittleAlien is " + b.getColor(0).toString());
System.out.println("Alien of type LittleAlien is " + b.getColor(1).toString());
螢幕輸出為:
java面向代碼調優的設計模式之flyweight pattern