享元模式 -- 设计模式

享元模式(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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值