首页 > 其他 > 详细

享元模式 -- 设计模式

时间:2019-04-02 11:23:40      阅读:117      评论:0      收藏:0      [点我收藏+]

享元模式(Flyweight Pattern)主要用于减少创建对象的数量,以减少内存占用和提高性能。

思考: 通过复用对象来完成工作, 减少对象的创建数量

package day0319.FlayweightPattern;

import java.util.HashMap;
import java.util.Map;

public class Demo{

    public static void main(String[] args){

        ShapeFactory shapeFactory = new ShapeFactory();
        Circle red = (Circle) shapeFactory.getCircle("red");
        red.setXYR(3, 3, 3);
        red.draw();

        Circle bigred = (Circle) shapeFactory.getCircle("red");
        bigred.setXYR(3, 3, 10);
        bigred.draw();

        Circle green = (Circle) shapeFactory.getCircle("green");
        green.setXYR(3, 3, 10);
        green.draw();
    }
}

class ShapeFactory {

    Map<String, Shape> hashMap = new HashMap<>();

    public Shape getCircle(final String color) {
        Shape shape = hashMap.get(color);
        if (shape != null) {
            System.out.println("[BUILDING] get a circle from map");
            return shape;
        } else {
            System.out.println("[BUILDING] creating a new circle");
            Circle circle = new Circle(){{
                setColor(color);
            }};
            hashMap.put(color, circle);
            return circle;
        }
    }
}


interface Shape {
    void draw();
}

class Circle implements Shape {

    private int x, y, r;
    private String color;

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

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

    public void setR(int r){
        this.r = r;
    }


    public void setXYR(int x, int y, int r){
        this.x = x;
        this.y = y;
        this.r = r;
    }

    public void setColor(String color){
        this.color = color;
    }

    @Override
    public void draw(){
        String template = "%s circle(%s, %s) with %s radis";
        System.out.println(String.format(template, this.color, x, y, r));
    }
}

  

享元模式 -- 设计模式

原文:https://www.cnblogs.com/litran/p/10641390.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!