设计模式(4)享元模式

享元模式(Flyweight Pattern)主要用于减少创建的对象数量,并减少内存占用并提高性能。 这种类型的设计模式属于结构模式,因为该模式提供了减少对象计数的方法,从而改善应用的对象结构。

第一步:创建一个Shape接口,代码如下

/**
 * @author 欧阳飘
 */
public interface Shape {
   void draw();
}

第二步:创建一个实现相同接口的具体类Circle

package com.test.flyPatternMode;

/**
 * @author 欧阳飘
 */
public class Circle implements Shape {
   //颜色
   private String color;
   //圆心位置 x,y
   private int x;
   private int y;
   //圆的半径
   private int radius;

   public Circle(String color){
      this.color = color;        
   }

   public void setX(int x) {
      this.x = x;
   }

   public void setY(int y) {
      this.y = y;
   }

   public void setRadius(int radius) {
      this.radius = radius;
   }

   @Override
   public void draw() {
      System.out.println("画圆:  [Color : " + color + ", x : " + x + ", y :" + y + ", radius :" + radius);
   }
}

第三步:创建一个工厂根据给定的信息生成具体类的对象

/**
 * @author 欧阳飘
 */

public class ShapeFactory {
   //用这个Map来存放形状对象, key是颜色
   private static final HashMap<String, Shape> circleMap = new HashMap<String,Shape>();

   //如果不存在, 那么就创建对象, 如果存在那么直接从Map中去取
   public static Shape getCircle(String color) {
      Circle circle = (Circle)circleMap.get(color);
      if(circle == null) {
         circle = new Circle(color);
         circleMap.put(color, circle);
         System.out.println("创建圆对象------颜色为: " + color);
      }
      return circle;
   }
}

第四步:使用工厂并通过传递诸如颜色的信息来获得具体类的对象

/**
 * @author 欧阳飘
 */

public class FlyweightPatternDemo {
   private static final String colors[] = { "Red", "Green", "Blue", "White", "Black" };
   public static void main(String[] args) {
      for(int i=0; i < 20; ++i) {
         Circle circle = (Circle)ShapeFactory.getCircle(getRandomColor());
         circle.setX(getRandomX());
         circle.setY(getRandomY());
         circle.setRadius(100);
         circle.draw();
      }
   }
   private static String getRandomColor() {
      return colors[(int)(Math.random()*colors.length)];
   }
   private static int getRandomX() {
      return (int)(Math.random()*100 );
   }
   
   private static int getRandomY() {
      return (int)(Math.random()*100);
   }
}

猜你喜欢

转载自my.oschina.net/u/3013327/blog/1563979