设计模式(4)享元模式

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

第一步:建立一个Shape接口,代码以下dom

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

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

package com.test.flyPatternMode;性能

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

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

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

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

相关文章
相关标签/搜索