当前位置: 移动技术网 > IT编程>软件设计>设计模式 > 设计模式系列 - 享元模式

设计模式系列 - 享元模式

2018年12月26日  | 移动技术网IT编程  | 我要评论

享元模式主要通过共享对象的方式来减少对象的创建。

介绍

在复杂系统中,频繁创建对象是一件很耗资源的操作,为了节约系统有限的资源,我们有必要通过某种技术来减少对象的创建。在 aspnetcore 大量使用了 依赖注入 技术从而达到对象的集中式管理。

类图描述

由上图可知,通过定义一个 ishape 接口来约束实体类行为,circle 为具体的实体类,shapefactory 为享元工厂,用于统一所有实体类的初始化操作。

代码实现

1、定义行为接口

public interface ishape
{
    void draw();
}

2、定义对象实体

public class circle:ishape
{
    private string color;
    private int x;
    private int y;
    private int radius;
    public circle(string color)
    {
        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;
    public void draw() => console.writeline($"circle:draw()[color:{color},x={x},y={y},radius:{radius}]");
}

3、定义享元工厂

public class shapefactory
{
    private static dictionary<string, ishape> circlemap = new dictionary<string, ishape>();

    public static ishape getcircle(string color)
    {
        circlemap.trygetvalue(color, out var circle);

        if (circle != null) return circle;
        circle = new circle(color);
        circlemap.add(color, circle);
        console.writeline($"creating circle of color:{color}");

        return circle;
    }
}

4、上层调用

class program
{
    private static string[] colors = new[] {"red", "green", "blue", "white", "black"};
    private static random random = new random();

    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();
        }

        console.readkey();
    }

    private static string getrandomcolor()
    {
        return colors[random.next(0, colors.length)];
    }

    private static int getrandomx()
    {
        return random.next(0, colors.length) * 100;
    }

    private static int getrandomy()
    {
        return random.next(0, colors.length) * 100;
    }
}

总结

如果系统中需要大量初始化相似对象,系统资源使用紧张,此时使用享元模式较为合适,但是需要注意的是要合理区分内部操作和外部操作,否则很容易引起线程安全的问题。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网