享元模式(Flyweight Pattern)主要用于减小建立的对象数量,并减小内存占用并提升性能。 这种类型的设计模式属于结构模式,由于该模式提供了减小对象计数的方法,从而改善应用的对象结构。设计模式
第一步:建立一个Shape接口,代码以下dom
/** * @author 欧阳飘 */ public interface Shape { void draw(); } |
第二步:建立一个实现相同接口的具体类Circleide
package com.test.flyPatternMode;性能 /** public Circle(String color){ public void setX(int x) { public void setY(int y) { public void setRadius(int radius) { @Override |
第三步:建立一个工厂根据给定的信息生成具体类的对象
/** public class ShapeFactory { //若是不存在, 那么就建立对象, 若是存在那么直接从Map中去取 |
第四步:使用工厂并经过传递诸如颜色的信息来得到具体类的对象
/** 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); } } |