java面向代码调优的设计模式之flyweight 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){

扫描二维码关注公众号,回复: 1724774 查看本文章

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

屏幕输出为:

猜你喜欢

转载自www.cnblogs.com/mrchi/p/9219160.html
今日推荐