FlyWeight模式
来源:互联网 发布:持仓异动指标源码 编辑:程序博客网 时间:2024/04/29 19:06
public interface Shape { void draw();}
public class Circle implements Shape { private String color; private int x; private int y; private int radius; public Circle(String color) { this.color = color; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getRadius() { return radius; } public void setRadius(int radius) { this.radius = radius; } @Override public void draw() { System.out.println("Circle:Draw() [Color:" + color + ",x:" + x + ",y:" + y + ", radius: " + radius); }}
import java.util.HashMap;public class ShapeFactory { private static final HashMap<String, Shape> circleMap = new HashMap<String, Shape>(); 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("Creating circle of color :"+color); } return circle; }}
public class FlyweightPatternDemo { /** * 执行过程: * 1、设置colors的颜色 * * **/ 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(); } } /** * 返回随机颜色 * @return */ 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); }}
阅读全文
0 0
- flyweight模式
- Flyweight模式
- FlyWeight模式
- Flyweight模式
- Flyweight模式
- Flyweight 模式
- Flyweight模式
- FlyWeight模式
- FlyWeight模式
- Flyweight 模式
- FlyWeight模式
- FlyWeight模式
- FlyWeight模式
- Flyweight模式
- Flyweight模式
- Flyweight模式
- Flyweight模式
- Flyweight 模式
- 算法谜题72 标记方格2
- C++基础---无返回值函数(void函数)
- 2017年五月二十五日 NO.1 开始使用CSDN--了解MarkDown的语法
- 一些优秀的网站
- Go Timer的使用
- FlyWeight模式
- C++ 拓扑排序
- 一次完整的HTTP请求与响应涉及了哪些知识?
- 算法谜题73 逮公鸡
- ucosII 信号量的原理及应用
- 继承(二)
- spring 框架的xml文件如何读取properties文件数据
- jquery ajax POST 例子详解
- 嵌入式学习 DAY1 JZ2440 V3 裸版烧系统