享元模式
来源:互联网 发布:三菱m70cnc传输软件 编辑:程序博客网 时间:2024/06/07 06:43
享元模式
void draw();
}
public class Circleimplements Shape{
private Stringcolor;
privateint x;
privateint y;
privateint radius;
public Circle(Stringcolor){
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("Circle: Draw() [Color : " +color
+", x : " +x +", y :" +y +", radius :" +radius);
}
}
public class ShapeFactory {
private static final HashMap<String, Shape> circleMap = new HashMap<>();
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);
}
returncircle;
}
}
使用
private static final String colors[] =
{ "Red","Green", "Blue","White", "Black" };
public static void main(String[] args) {
for(inti=0; i < 20; ++i) {
Circle circle =
(Circle)ShapeFactory.getCircle(getRandomColor());
circle.setX(getRandomX());
circle.setY(getRandomY());
circle.setRadius(100);
circle.draw();
}
}
privatestatic String getRandomColor() {
returncolors[(int)(Math.random()*colors.length)];
}
privatestatic int getRandomX() {
return (int)(Math.random()*100 );
}
privatestatic int getRandomY() {
return (int)(Math.random()*100);
}
一个圆共有的属性有圆点、半径、颜色,这些在代码内是可以共享的,不过他们的值可以动态设置。这个就是上面的提到的内部状态和外部状态。属性是内部状态- 深入浅出享元模式
- 享元模式
- 享元(FlyWeight)模式
- 享元模式
- 享元模式
- 享元模式
- 享元模式
- 享元模式Flyweight
- 享元模式
- 享元模式
- 享元模式
- FlyWeight 享元模式
- 享元模式(Flyweight)
- 享元模式
- 享元模式
- 享元模式
- 享元模式
- 享元模式 ---flyweight
- AUTOSAR CAN Network Management 介绍
- 学生信息管理系统错误总结之3021
- 【Sort】350. Intersection of Two Arrays II
- 84. Largest Rectangle in Histogram
- 今日头条|张一鸣:我遇到的优秀年轻人的5个特质 头条招聘 2016-08-17 12:11 文| 张一鸣 今日头条|张一鸣:我遇到的优秀年轻人的5个特质 文章整理自今日头条张一鸣8月12日在“20
- 享元模式
- P1908 逆序对
- Hive中的join操作原理和优化
- 排序
- Python 07 函数的定义与调用
- 内置对象--Array对象篇
- cout不明确
- POJ3984《迷宫问题》
- POJ 2429 GCD & LCM Inverse(大整数素因子分解+二进制枚举)